简体   繁体   中英

jQuery Form Validation — Correct Submission Not Clearing Errors

Working on form validation in jQuery. All of my validations seem to be working correctly.

See JSFiddle here.

If you submit the form with no data, all of the correct errors appear.

If you fix one of the fields, the error message for that field does not clear.

I think it probably is something wrong with my logic, but unsure if there is an easy way to try and check the validation again?

My code for submit in jQuery is here. The first four validate functions are checking for errors and displaying errors if there are any. If there are any errors with anything, the form is prevented from submitting. If there is no error, an alert is displayed and the submission is allowed. I know that the problem is that after that first if statement finds an error - there is no way to look and see if the error is fixed and to clear that error. So I'm stumped on where to go with this - would it be better off in a loop maybe?

// On Form Submission Validate Form
$("#contact_submit button").click(function(event){
    error_name = validateName();
    error_email = validateEmail();
    error_activity = validateActivities();
    isCreditIssue = validateCredit();
    event.preventDefault();

    var valid = true;

    if ((error_name) || (error_email) || (error_activity) || (isCreditIssue)){
        console.log("errors");
        valid = false;
    } else {
        alert('GREAT! form completed');
        valid = true;
    }
    if (valid) {
    return;
    }

You left out hide statements when the form values become valid at many places. Just an example (inside validateZip ):

if ((!errorZip)||(zip!= 5)){
    $(".error_zip").show();
    errorZip = true;
    console.log('zip issue');
} else {
    errorZip = false;
}

You should replace it with this:

if ((!errorZip)||(zip!= 5)){
    $(".error_zip").show();
    errorZip = true;
    console.log('zip issue');
} else {
    $(".error_zip").hide();
    errorZip = false;
}

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