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.

7 comments:

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 !

Anonymous said...

hi

where do i include these functions?

Anonymous said...

$(function() {
var validationSettings = $.data($('#formToValidateId').get(0), 'validator').settings;
validationSettings.onkeyup = false;
validationSettings.onfocusout = false;
});

right now my input field is validated only on tab out. on the second instance, the keyup is validated. how to get the keyup event to fire on the first instance.

Cindy Dy said...

It's enjoyable to learn more and more from your blog. Thanks for sharing.

www.gofastek.com