2014-10-07 106 views
0

我正在处理一个带有几个文本框和一个提交按钮的Web窗体。当点击提交按钮时,我应该验证必填字段是否都有输入,并且年龄字段只是数字。例如,用户可以输入56,但56岁,不应被接受。如果用户输入无效输入或将必填字段留空,则相应文本框周围的边框应变为红色。使用Javascript验证输入

但是,现在编写我的代码,所有必填字段都将变成红色,而不管输入如何。任何想法如何解决这个问题,并使页面遵循我列出的几条规则?

最接近代码

<html> 
    <head> 
    <title>Project 4</title> 

    <style type="text/css"> 
     body { 
     background-color: black; 
     color: blue; 
     text-align: center; 
     border: 2px double blue; 
     } 
    </style> 
    </head> 

    <body> 
     <h1>Welcome to my Web Form!</h1> 
     <p> 
     Please fill out the following information.<br> 
     Please note that fields marked with an asterisk (*) are required. 
     </p> 
      <form name="myForm" id="myForm" onsubmit="return validateForm()"> 
      *Last Name: <br> 
      <input type="text" id="lastname"> 
      <br> 
      First Name: <br> 
      <input type="text" id="firstname"> 
      <br> 
      *Hobbies (separate each hobby with a comma): <br> 
      <input type="text" id="hobbies"> 
      <br> 
      Pets: 
      <div id="petsContainer"> 
      <input type="text" id="pets"> 
      <input type="button" id="addPet" value="Add Pet"> 
      </div> 
      <br> 
      Children: 
      <div id="childContainer"> 
      <input type="text" id="children"> 
      <input type="button" id="addKid" value="Add Child"> 
      </div> 
      <br> 
      *Address: <br> 
      <input type="text" id="address"> 
      <br> 
       *Phone Number:<br> 
      <input type="text" id="phone"> 
       <br> 
      *Age: <br> 
      <input type="text" id="age"> 
      <br> 
       <input type="submit" value="Submit"> 
      </form> 

      <script type="text/javascript"> 
       var validatePhoneOnKeyUpAttached = false; 
      var validateLNameOnKeyUpAttached = false; 
      var validateHobbiesOnKeyUpAttached = false; 
      var validateAddressOnKeyUpAttached = false; 
      var validateAgeOnKeyUpAttached = false; 

       function validateForm() { 
         if(!validatePhoneOnKeyUpAttached) { 
          document.getElementById("phone").onkeyup = checkPhone; 
          validatePhoneOnKeyUpAttached = true; 
         } 
       else if(!validateLNameOnKeyUpAttached) { 
        document.getElementById("lastname").onkeyup = checkEmpty; 
        validateLNameOnKeyUpAttached = true; 
       } 
       else if(!validateHobbiesOnKeyUpAttached) { 
        document.getElementById("hobbies").onkeyup = checkEmpty; 
        validateHobbiesOnKeyUpAttached = true; 
       } 
       else if(!validateAddressOnKeyUpAttached) { 
        document.getElementById("address").onkeyup = checkEmpty; 
        validateAddressOnKeyUpAttached = true; 
       } 
       else if(!validateAgeOnKeyUpAttached) { 
        document.getElementById("age").onkeyup = checkEmpty; 
        document.getElementById("age").onkeyup = checkAge; 
        validateAgeOnKeyUpAttached = true; 
       } 

         return checkEmpty() && checkPhone() && checkAge(); 
       } 

       function checkPhone() { 
         var phone = document.forms["myForm"]["phone"].value; 
         var phoneNum = phone.replace(/[^\d]/g, ''); 
         if(phoneNum.length > 6 && phoneNum.length < 11) { 
          document.getElementById("phone").style.borderColor="transparent"; 
          return true; 
        } 
         else if(phoneNum.length < 7 || phoneNum.length > 10) { 
          document.getElementById("phone").style.borderColor="red"; 
          return false; 
         } 
       } 

      function checkEmpty() { 
       var lname = document.forms["myForm"]["lastname"].value; 
       var pNum = document.forms["myForm"]["phone"].value; 
       var hobs = document.forms["myForm"]["hobbies"].value; 
       var live = document.forms["myForm"]["address"].value; 
       var yr = document.forms["myForm"]["age"].value; 
       document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent"; 
       document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent"; 
       document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent"; 
       document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent"; 
       document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent"; 
      } 

      function checkAge() { 
       var age = document.getElementById("age").value; 
       if(isNan(age)) { 
        return false; 
       } 
       else { 
        document.getElementById("age").style.borderColor="red"; 
        return true; 
       } 
      } 

      document.getElementById("addPet").onclick=function() { 
       var div = document.getElementById("petsContainer"); 
       var input = document.createElement("input"); 
       input.type = "text"; 
         input.name = "pats[]"; 
       div.appendChild(document.createElement("br")); 
       div.appendChild(input); 
      } 

      document.getElementById("addKid").onclick=function() { 
       var div = document.getElementById("childContainer"); 
       var input = document.createElement("input"); 
       input.type = "text"; 
         input.name = "child[]"; 
       div.appendChild(document.createElement("br")); 
       div.appendChild(input); 
      } 

      </script> 
    </body> 
</html> 

我目前遇到的问题是,当我点击提交按钮,所有字段变成红色的一瞬间,但随后回到正常色并且输入被擦除。有关如何解决这个问题的任何想法?

+0

你的问题是什么? – 2014-10-07 03:18:00

+0

@黑洞,如何修复我的代码,以便正确执行输入验证 – 2014-10-07 05:51:24

回答

1

通过在一个代码块中包含所有borderColor =“red”语句,即使只有其中一个验证失败,您也可以将该样式应用于所有输入。您需要分离出每个语句,以便它仅适用于个别领域(S)验证失败:

document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent"; 
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent"; 
... 

另外,我使用的是三元运算符? :清理代码。这些语句会替代你写的if-else块。

+0

嗨,我用这个来修复我的代码,但我遇到了一个问题,当我点击提交按钮时,所有的字段都变成了红色,无论是不是他们有输入,然后回到正常的颜色和输入被删除。我已经更新了小提琴以反映这一点。 http://jsfiddle.net/jmaxu6un/3/ – 2014-10-07 03:41:53

0

我正在使用以下JavaScript函数为了验证我的表单变量。希望这些对你有帮助。

var W3CDOM = (document.getElementsByTagName && document.createElement); 
window.onload = function() { 
    document.forms[0].onsubmit = function() { 
     return validate() 
    } 
} 
function validate() { 
    validForm = true; 
    firstError = null; 
    errorstring = ''; 
    var x = document.forms[0].elements; 
    for (var i = 0;i < x.length;i++) { 
     if (!x[i].value) { 
      validForm = false; 
      writeError(x[i], 'This field is required'); 
     } 
    } 
// This can be used to validate input type Email values 
    /* if (x['email'].value.indexOf('@') == -1) { 
        validForm = false; 
        writeError(x['email'],'This is not a valid email address'); 
      } 
      */ 
    if (!W3CDOM) 
     alert(errorstring); 
    if (firstError) 
     firstError.focus(); 
    return validForm; 
} 
function writeError(obj, message) { 
    validForm = false; 
    //if (obj.hasError) return false; 
    if (W3CDOM) { 
     obj.className += ' error'; 
     obj.onchange = removeError; 
     var sp = document.createElement('span'); 
     sp.className = 'error'; 
     sp.appendChild(document.createTextNode(message)); 
     obj.parentNode.appendChild(sp); 
     obj.hasError = sp; 
    } else { 
     errorstring += obj.name + ': ' + message + '\n'; 
     obj.hasError = true; 
    } 

    if (!firstError) 
     firstError = obj; 
    return false; 
} 
function removeError() { 
    this.className = this.className.substring(0, this.className.lastIndexOf(' ')); 
    this.parentNode.removeChild(this.hasError); 
    this.hasError = null; 
    this.onchange = null; 
} 

您可以在表单提交后立即调用验证,如下所示。

<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">