简体   繁体   中英

How to validate multiple fields at the same time using JQuery

I have created a form that validates using JQuery and 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.

Here is My 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.

Then validateForm could be something like

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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