I've attempted binding to the change eve开发者_JAVA百科nt of all inputs in the form, and checked to see if there are any validation messages on the page. The problem is that validation seems to occur after the change event, so I am checking before the errors appear on the page. I'm looking for some way to run my script after the client-side validation takes place.
I'm using MVC 2 with DataAnnotation attributes on my VM.
Here's something I just hacked together that wraps the original parseElement
and invalidHandler
functions, allowing you to add your own logic.
(function($) {
$.validator.unobtrusive.parseElement = (function (original) {
return function (element, skipAttach) {
original.call(this, element, skipAttach);
var form = $(element).parents("form:first")[0];
var validationInfo = $(form).data('unobtrusiveValidation');
if (validationInfo) {
var handler = validationInfo.options.invalidHandler;
var newhandler = function () {
console.log('Here is where you can do additional handling');
handler.call(this);
};
validationInfo.options.invalidHandler = $.proxy(newhandler, form);
} else {
// this didn't work.
}
}
})($.validator.unobtrusive.parseElement);
})(jQuery);
Notice, though, that this is an immediate function, not the jQuery function which is equivalent to document.onload.
This is replacing the $.validator.unobtrusive.parseElement
with a new function that calls the original to ensure the validationInfo.options.invalidHandler
is applied to the parent form, which then allows you to wrap that handler with the newhandler
function.
Edit: The above answer will only work for MVC3 and unobtrusive validation.
To perform some additional functionality with $.validator
when the form is invalid...
$('form:first').bind("invalid-form.validate", function () {
alert("invalid!");
});
精彩评论