Search code examples
jqueryjquery-validate

How to clear jQuery validation error messages?


I am using the jQuery validation plugin for client side validation. Function editUser() is called on click of 'Edit User' button, which displays error messages.

But I want to clear error messages on my form, when I click on 'Clear' button, that calls a separate function clearUser().

function clearUser() {
    // Need to clear previous errors here
}

function editUser(){
    var validator = $("#editUserForm").validate({
        rules: {
            userName: "required"
        },
        errorElement: "span",
        messages: {
            userName: errorMessages.E2
        }
    });

    if(validator.form()){
        // Form submission code
    }
}

Solution

  • You want the resetForm() method:

    var validator = $("#myform").validate(
       ...
       ...
    );
    
    $(".cancel").click(function() {
        validator.resetForm();
    });
    

    I grabbed it from the source of one of their demos.

    Note: This code won't work for Bootstrap 3.