JQuery Validation Hooks – ASP.Net MVC
ASP.Net MVC comes with some great JQuery validation features, but sometimes you need just a little more to accomplish your task. I recently was trying to take advantage of Twitter Bootstrap’s error highlighting. If you have used JQuery validation in MVC, you’ll notice that it only marks the input that failed to validate, but doesn’t do much else. This is great for highlighting the field, but I needed to highlight the label, the helping text, and the input that I have present in my form.
I knew JQuery has a feature to let you bind to events, but I wondered if someone had already run into my particular situation. Surely someone had, and they created a great addition to ASP.Net MVC unobtrusive file that let’s you bind to different events. It’s called jQuery Validate Hooks.
The library let’s you:
- 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
Check it out it’s awesome. jQuery Validate Hooks.
Ultimately my code to utilize this library looked like this:
$(function () {
// Validation
$('form').addTriggersToJqueryValidate().triggerElementValidationsOnFormValidation();
$('form').formValidation(function (element, result) {
$(element).find('input').each(function (index, value) {
markControlGroup(value);
});
});
$('form input').on('keyup', function () {
markControlGroup(this);
});
});
function markControlGroup(input) {
var el = $(input);
if (el.hasClass('input-validation-error')) {
el.parents('div.control-group').addClass('error');
} else {
el.parents('div.control-group').removeClass('error');
}
}
With the end result looking like this on my form.

That’s pretty cool, and the code above still leverages all the existing validation code that I have. I love JQuery and thanks to the author of this little script, because it is amazing. Also thanks to Twitter for Bootstrap.
