Wednesday, April 21, 2010

Add InvalidHandler after jQuery validator initialization

If you have a problem where you need to add the option 'invalidHandler' to your jqueryValidate (jQuery Validation Plugin) after it has been initialized, this is how it can be done:
$(document).ready(function(){
$("#contactForm").bind('invalid-form.validate',
function(event, validator) {
alert('validation failed!');
}
);
});


Regularly you would add this on initialization:
$(document).ready(function(){
$('#contactForm').validate({
invalidHandler:
function(event, validator) {
alert('validation failed!');
},
rules: {}
});
});


Note: invalidHandler will be called when validation of form fails on submit (e.g. values for a field is missing or such).

This might work for other options of the jqueryValidate plugin, but I'm not sure which property to use. I found the property to bind to in the jquery.validate.js file, you might want to look there.

4 comments:

  1. Thanks useful for overriding MVC validation

    ReplyDelete
  2. I just proposed the following change:

    if (this.settings.invalidHandler) {
    $(this.currentForm).bind("invalid-form.validate", function (event, validator) {
    validator.settings.invalidHandler(event, validator);
    });
    }

    https://github.com/jzaefferer/jquery-validation/issues/765

    ReplyDelete
    Replies
    1. Andy:
      Hey thanks for the update, I'll check it out. It would be great to have this added officially, you never know when hacks like this will break your page because of an update in the library. :)

      Everybody:
      Go support jQuery Validation Plugin at http://jqueryvalidation.org/ it's a great plugin!

      Delete
  3. Thank you for this post, I was trying to simply redefine invalidHandler on the existing validator. After pulling some of my hair out, came across this post and all is well!

    ReplyDelete