Friday, March 9, 2012

ASP.NET MVC 3: Configuring unobtrusive validation

ASP.NET MVC 3 ofeers client side validation through the unobtrusive javascript and jQuery validation plugins. Most of the time the default behavior is fine, but what if you want to tweak the validation configuration?
Only validate the form fields when the form is submitted:
$(function() {
 var validationSettings = $.data($('#formToValidateId').get(0), 'validator').settings;
 validationSettings.onkeyup = false;
 validationSettings.onfocusout = false;

As you can see, it’s possible to change some settings through the  validator settings object. By setting  the onkeyup and onfocusout properties to false, the validation on blur and key up will be disabled.
Disable the validation on input fields with class ignore.
$(function() {
 var validationSettings = $.data($('#formToValidateId').get(0), 'validator').settings;
 validationSettings.ignore = '.ignore';

Setting the ignore property of validator settings object to .ignore will tell the jQuery validation plugin to ignore all input elements with class ignore during validation. 

Of course there are a lot more options you can configure. For a complete list of jQuery validation options have a look here.


Brandon Kobel said...

Thank you, I was having trouble finding this, this worked perfectly.

Anonymous said...

I had to disable unobtrusive on particular input field and this is just what I need. Thank you

Krzysztof Jeske said...

"Only validate the form fields when the form is submitted"

Great, thanks!

Anonymous said...

Perfect ! thanks a lot !