If you're using ASP.NET MVC3, it uses jQuery Validate to do client-side validations. Instead of using jQuery Validate directly, however, it wraps it with its own jQuery plugin called jQuery.Validate.Unobtrusive. jQuery.Validate.Unobtrusive sets up jQuery Validate for you, behind the scenes, so you don't have an opportunity to customize your jQuery Validate settings at all!
We've been running into trouble with this when we've been doing our own custom client-side validations. We need a way to integrate with the build-in ASP.NET MVC3 validation so we can:
- Find out when our form's client-side validation runs and do something custom, if it fails
- Find out when a particular element's client-side validation runs and do something custom if it passes or fails
We might extend this to be able to hook into other things, like jQuery Validate's submitHandler
(which allows you to override what happens when the form is valid and ready to be submitted).
<script type="text/javascript" src="jquery.validate.hooks.js"></script>
$(document).ready(function(){
// we're assuming that this has already been run (which MVC3 does automatically)
// $('form').validate();
// running this overrides some jQuery Validate stuff so we can hook into its validations.
// triggerElementValidationsOnFormValidation is optional and will fire off all of your
// element validations WHEN the form validation runs ... it requires jquery.validate.unobtrusive
$('form').addTriggersToJqueryValidate().triggerElementValidationsOnFormValidation();
// You can bind to events that the forms/elements trigger on validation
$('form').bind('formValidation', function(event, element, result) {
console.log(['validation ran for form:', element, 'and the result was:', result]);
});
// Or you can use the helper functions that we created for binding to these events
$('form').formValidation(function(element, result) {
console.log(['validation ran for form:', element, 'and the result was:', result]);
});
$('input.something').elementValidation(function(element, result) {
console.log(['validation ran for element:', element, 'and the result was:', result]);
});
$('input#address').elementValidationSuccess(function(element) {
console.log(['validations just ran for this element and it was valid!', element]);
});
$('input#address').elementValidAndInvalid(function(element) {
console.log(['validations just ran for this element and it was valid!', element]);
}, function(element){
console.log(['validations just ran for this element and it was INVALID!', element]);
});
});
Thank you so much for these hooks. Works perfectly for me! Wonderful! Perhaps you could put some Author/Copyright stuff in, so credit goes where it is due.