简体   繁体   English

如何使用JQuery同时验证多个字段

[英]How to validate multiple fields at the same time using JQuery

I have created a form that validates using JQuery and JavaScript. 我创建了一个使用JQuery和JavaScript进行验证的表单。 The only problem is, would be that it validates one field at a time. 唯一的问题是,它将一次验证一个字段。 So the user has to correct the first field first and then press submit again to see if the next field is valid. 因此,用户必须先更正第一个字段,然后再按一次提交以查看下一个字段是否有效。

What I would like to to do, is have the JQuery validate the whole form after pressing submit and show all the applicable error messages. 我想做的是让JQuery在按下Submit之后验证整个表单并显示所有适用的错误消息。

Here is My JS: 这是我的JS:

function validateUserName()
{
    var u = document.forms["NewUser"]["user"].value
    var uLength = u.length;
    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if (u == null || u == "")
    {

        $("#ErrorUser").text("You Left the Username field Emptyyy");
        return false;
    }
    else if (uLength < 4 || uLength > 11)
    {
        $("#ErrorUser").text("The Username must be between 4 and 11 characters");
        return false;
    }
    else if (illegalChars.test(u))
    {
        $("#ErrorUser").text("The Username contains illegal charectors men!");
        return false;
    }
    else
    {
        return true;
    }
}

function validatePassword()
{
    var p = document.forms["NewUser"]["pwd"].value
    var cP = document.forms["NewUser"]["confirmPwd"].value
    var pLength = p.length;
    if (p == null || p == "")
    {
        $("#ErrorPassword1").text("You left the password field empty");
        return false;
    }
    else if (pLength < 6 || pLength > 20)
    {
        $("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
        return false;
    }
    else if (p != cP)
    {
        $("#ErrorPassword1").text("Th passwords do not match!");
        return false;
    }
    else
    {
        return true;
    }
}

function validateEmail()
{
    var e = document.forms["NewUser"]["email"].value
    var eLength = e.length;
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;

    if (eLength == "" || eLength == null)
    {

        $("#ErrorEmail").text("You left the email field blank!");
        return false;
    }
    else if (e.match(illegalChars))
    {

        $("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
        return false;
    }
    else
    {
        return true;
    }
}

function validateFirstName()
{
    var f = document.forms["NewUser"]["fName"].value;
    var fLength = f.length;
    var illegalChars = /\W/;

    if (fLength > 20)
    {
        $("#ErrorFname").text("First Name has a max of 20 characters");
        return false;
    }
    else if (illegalChars.test(f))
    {
        $("#ErrorFname").text("Numbers,letter and underscores in first name only");
        return false;
    }
    else
    {
        return true;
    }


}

function validateLastName()
{
    var l = document.forms["NewUser"]["lName"].value;
    var lLength = l.length;
    var illegalChars = /\W/;

    if (lLength > 100)
    {
        $("#ErrorLname").text("Last Name has a max of 100 characters");
        return false;
    }
    else if (illegalChars.test(f))
    {
        $("#ErrorLname").text("Numbers,letter and underscores in last name only");
        return false;
    }
    else
    {
        return true;
    }


}

function validateForm()
{
    valid = true;
    //call username function
    valid = valid && validateUserName();

    //call password function
    valid = valid && validatePassword();

    //call email function
    valid = valid && validateEmail();

    //call first name function
    valid = valid && validateFirstName();

    //call first name function
    valid = valid && validateLastName();

    return valid;
}

And here is my submit form code: 这是我的提交表单代码:

$('#your-form').submit(validateForm);

Instead of returning true or false return a string containing the error and an empty string if no error was found. 代替返回truefalse返回包含错误的字符串,如果未发现错误,则返回空字符串。

Then validateForm could be something like 然后validateForm可能像

function validateForm()
{
    error = "";
    //call username function
    error += "\n"+validateUserName();

    //call password function
    error += "\n"+validatePassword();
    ...
    if(error === ""){
        return true;
    }
    $("#ErrorLname").text(error);
    return false;
}

Working Fiddle 工作小提琴

You need to access all the fields and check if the field is valid r not. 您需要访问所有字段,并检查该字段是否有效,否则无效。 If the field is valid skip it, otherwise put the field in an array. 如果该字段有效,请跳过该字段,否则将其放入数组中。 When all the fields have been checked, then display the error fields from the array all at one time. 检查完所有字段后,一次显示数组中的所有错误字段。

var validate;
function validateUserName()
{
       validate = true;
        var u = document.forms["NewUser"]["user"].value
        var uLength = u.length;
        var illegalChars = /\W/; // allow letters, numbers, and underscores
        if (u == null || u == "")
        {
            $("#ErrorUser").text("You Left the Username field Emptyyy");
            validate     = false;
        }
        else if (uLength <4 || uLength > 11)
        {
            $("#ErrorUser").text("The Username must be between 4 and 11 characters");
            validate     = false;
        }
        else if (illegalChars.test(u)) 
        {
            $("#ErrorUser").text("The Username contains illegal charectors men!");
            validate     = false;
        }

}

    function validatePassword()
    {
        var p = document.forms["NewUser"]["pwd"].value
        var cP = document.forms["NewUser"]["confirmPwd"].value
        var pLength = p.length;
        if (p == null || p == "")
        {
            $("#ErrorPassword1").text("You left the password field empty");
           validate     = false;
        }
        else if (pLength < 6 || pLength > 20)
        {
            $("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
            validate     = false;
        }
        else if (p != cP)
        {
            $("#ErrorPassword1").text("Th passwords do not match!");
            validate     = false;
        }

    }

    function validateEmail()
    {
        var e = document.forms["NewUser"]["email"].value
        var eLength = e.length;
        var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
        var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

        if (eLength == "" || eLength == null) 
        {

            $("#ErrorEmail").text("You left the email field blank!");
            validate     = false;
        } 
        else if (e.match(illegalChars)) 
        {

            $("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
           validate     = false;
        } 

    }
    function validateFirstName()
    {
        var f = document.forms["NewUser"]["fName"].value;
        var fLength = f.length;
        var illegalChars = /\W/;

        if(fLength > 20)
        {
            $("#ErrorFname").text("First Name has a max of 20 characters");
            validate     = false;
        }
        else if (illegalChars.test(f))
        {
            $("#ErrorFname").text("Numbers,letter and underscores in first name only");
            validate     = false;
        }



    }

    function validateLastName()
    {
        var l = document.forms["NewUser"]["lName"].value;
        var lLength = l.length;
        var illegalChars = /\W/;

        if(lLength > 100)
        {
            $("#ErrorLname").text("Last Name has a max of 100 characters");
           validate     = false;
        }
        else if (illegalChars.test(f))
        {
            $("#ErrorLname").text("Numbers,letter and underscores in last name only");
            validate     = false;
        }

    }

function validateForm()   
{


     validateUserName();  
     validatePassword();    
     validateEmail();
     validateFirstName();
     validateLastName();

    return validate;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM