Javascript:基本原生表单验证 - 无法验证多个标准

时间:2015-07-16 19:50:18

标签: javascript validation

尝试学习如何验证表单输入。

输入需要: 1 - 不是空的。 2 - 仅包含字母字符(无数字)。

当我测试时(我现在只关注名字输入字段),如果我将其留空,它会给出正确的错误消息。但是,如果我在字段中数字,它将提交而不是显示错误消息。

我做错了什么?

HTML:

<form id="frm1">
   <fieldset id="controls">
    <div>
      <label for="firstname">First Name: </label>
       <input type="text" id="firstname">
        <span id="errFname" class="errmsg">&#42 You must enter a first name</span>
    </div>
    <div>
       <label for="lastname">Last Name: </label>
       <input type="text" id="lastname">
    </div>
    <div>
      <input type="submit" value="Submit">
    </div>
    </fieldset>
   </form>

SCRIPT:

    function checkForm(){


    document.getElementById("frm1").onsubmit=function() {


        //Validate first name: Required, Alphabetic (no numbers)
        if(document.getElementById("firstname").value === "") {

            document.getElementById("errFname").style.display = "inline";
            document.getElementById("firstname").focus();

            return false;

        }   else {

            return true;
        }//close if


        var alphaRegEx = /[a-zA-Z]/;
        var alphafname = document.getElementById("firstname").value;

        //check if first name has any digits
        if (!alphaRegEx.test(alphafname)){

            document.getElementById("errFname").style.display = "inline";
            document.getElementById("firstname").value="";
            document.getElementById("firstname").focus();

            return false;

        }   else {

            return true;

        }//close if


    }//close function

    return false;

}//close function (checkForm)


window.onload=checkForm;

1 个答案:

答案 0 :(得分:1)

问题是你在每个if块内返回,这使得整个submit回调返回。

您应该创建一个变量并仅在结尾处返回。像这样:

function checkForm(){


document.getElementById("frm1").addEventListener("submit", function(e) {
    var errors = [];

    //Validate first name: Required, Alphabetic (no numbers)
    if(document.getElementById("firstname").value === "") {

        document.getElementById("errFname").style.display = "inline";
        document.getElementById("firstname").focus();

        errors.push("required");

    }


    var alphaRegEx = /[a-zA-Z]/;
    var alphafname = document.getElementById("firstname").value;

    //check if first name has any digits
    if (!alphaRegEx.test(alphafname) && errors.length === 0){

        document.getElementById("errFname").style.display = "inline";
        document.getElementById("firstname").value="";
        document.getElementById("firstname").focus();

        errors.push("numeric");

    }
    //If you want, you can do something with your errors, if not, just return
    //You should rethink about handling all errors here showing/hiding messages, etc.
    if (errors.length > 0) {
      e.preventDefault();
      return false;
    }
    return true;


});//close function

}//close function (checkForm)