How to clear jQuery validation error messages?

Vicky picture Vicky · Jan 18, 2010 · Viewed 283.3k times · Source

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

Answer

Parrots picture Parrots · Jan 18, 2010

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.