HTML表单 - 表单一次性验证所有内容

时间:2016-06-02 12:53:23

标签: javascript html forms validation

我对我创建的HTML表单存在验证问题。当我验证第一个输入而没有在第二个输入中输入任何内容时,它似乎正在运行所有验证检查。我想要它,所以当我完成输入第一个输入时,它只验证那一个。然后我可以重复相同的过程到第二个输入。一旦两个输入都被正确验证,用户就可以提交。 我已经在JSFiddle中重新创建了我可以在这里找到的内容:http://jsfiddle.net/aJ2Tw/220/。任何帮助,将不胜感激!

代码:

<form action="" method="post" onsubmit="return FormValidation();" onchange="return FormValidation();">

        <div class="input-wrapper">
            <input type="text" placeholder="First Name" id="firstname" name="name"/>
                        <input type="text" placeholder="First Name" id="lastName" name="name"/>
        </div>



    <a href="#" onclick="FormValidation()">Submit</a>

    <script>
        function FormValidation(){
        //First Name Validation 
    var fn=document.getElementById('firstname').value;
    if(fn == ""){
        alert('Please Enter First Name');
        document.getElementById('firstname').style.borderColor = "red";
        return false;
    }else{
        document.getElementById('firstname').style.borderColor = "green";
    }
    if (/^[0-9]+$/.test(document.getElementById("firstname").value)) {
        alert("First Name Contains Numbers!");
        document.getElementById('firstname').style.borderColor = "red";
        return false;
    }else{
        document.getElementById('firstname').style.borderColor = "green";
    }
    if(fn.length <=2){
        alert('Your Name is To Short');
        document.getElementById('firstname').style.borderColor = "red";
        return false;
    }else{
        document.getElementById('firstname').style.borderColor = "green";
    }
  }
    </script> 

1 个答案:

答案 0 :(得分:1)

您可以创建创建标记,以跟踪输入字段是否已被触摸/更改一次。然后在FormValidation方法中,您只能对已触摸/更改的字段验证/显示错误。

    <form action="" method="post" onsubmit="return FormValidation();" onchange="return FormValidation();">

        <div class="input-wrapper">
            <input type="text" onchange="input1Changed()" placeholder="First Name" id="firstname" name="name"/>
            <input type="text" onchange="input2Changed()" placeholder="First Name" id="lastName" name="name"/>
        </div>

    <a href="#" onclick="FormValidation()">Submit</a>

    <script>
        function FormValidation(){
            if(isInput1Changed)
             {
              //validations/errors of Firstname
             }
            if(isInput2Changed)
             {
             //validations/errors of lastname
             }
          }
         var isInput1Changed = false;
         var isInput2Changed = false;
         function input1Changed(){
         isInput1Changed = true;
         }

         function input2Changed(){
         isInput2Changed = true;
         }
    </script>

希望你明白这一点!