onsubmit验证所有函数是否返回true

时间:2015-12-30 19:25:22

标签: javascript jquery html

我有大约6个表单输入,我有javascript运行验证,我将如何验证所有函数返回为真?这是我的javascript函数的两个示例

$(document).ready(function() {

//First Name Input Field
$( "#first_name" ).focusout(function() {
    if( this.value === "" || this.value === null ) {
        $( "#error_messages" ).text("First Name* is required so my response won't go to spam");
        return false;
    } else {
        var re = /^[A-Za-z-]+$/;
        if(re.test(document.getElementById("first_name").value)) {
            $( "#error_messages" ).text("");
            return true;
        } else {
            $( "#error_messages" ).text("First Name* not a valid name");
            return false;
        }
    }
});

//Last Name Input Field
$( "#last_name" ).focusout(function() {
    if( this.value === "" || this.value === null ) {
        $( "#error_messages" ).text("Last Name* is required so my response won't go to spam");
        return false;
    } else {
        var re = /^[A-Za-z-]+$/;
        if(re.test(document.getElementById("last_name").value)) {
            $( "#error_messages" ).text("");
            return true;
        } else {
            $( "#error_messages" ).text("Last Name* not a valid name");
            return false;
        }
    }
});
});

1 个答案:

答案 0 :(得分:0)

添加默认变量并设置为true。 当发生错误时,将值覆盖为false。

理念是:

    $(document).ready(function() {

    var firstnameStatus = true;
    var lastnameStatus = true;

    if(firstname have error){
   // your code
   var firstnameStatus = false;
}

if(lastname have error){
   // your code
   var lastnameStatus = false;
}

    if( firstnameStatus == true && lastnameStatus == true){
    alert('all fields true');
    }

    });