jQuery Validate resetForm() doesn't reset the onFocus validation

Ryan picture Ryan · Jan 24, 2012 · Viewed 8.9k times · Source

I have a form that is using jQuery Validate plugin for client side validation, and submits via AJAX. After the form is submitted, I would like it to reset itself. I have used the .resetForm() method to reset the fields, which works, but the problem is that the validate plugin still immediately tries to validate fields when they're focused, and gives an error before giving the new submission a chance to enter their input.

Example Flow:

  • Trigger validation initially
  • Fix Validation, submit form via AJAX
  • Call .resetForm(), fields are successfully cleared out
  • Attempt to fill out form again
  • Focus on a field (which in my case has email validation)
  • Before giving you a chance to enter input, it validates and says it is incorrect.

Typically the plugin will let your enter your input before telling you that it's incorrect. Is there any way to truely reset the form and not have the validation occur on focus again, without turning off on focus validation all together?

Thanks, and here's a cleaned up/simplified code samples!

    // Validation
    $('#registerForm').validate({
        submitHandler: function(form) {

            $(form).ajaxSubmit({
                success: function(response) {

                    if( response == 'success' ) {
                        resetMyForm();
                    }
                    else {
                        alert('unsuccessful');
                    }

                }
            })
        }
    });

})




function resetMyForm() {

        $('#registerForm').resetForm();
        v.prepareForm();  // Tried adding this, no help
        v.hideErrors();  // Tried adding this, no help

}

Answer

Ryley picture Ryley · Jan 30, 2012

You need to reset the form and run the Validation plugin method resetForm like this:

var v = $("form").validate({
    submitHandler: function(form) {
            //resetForm is a method on the validation object, not the form
            v.resetForm(); 
            form.reset();
    }
});

That seemed to take care of any issues I saw while following your workflow. See this: http://jsfiddle.net/nxXNz/27/