jQuery Validation and ASP.NET MVC Forms


We have a standard that is part of our definition of done that includes adding client side validation to any page that contains a form. We always require server side validation, but I really like this standard since I’m all about progressive enhancement. We have adopted Jörn Zaefferer’s Validation plug-in (to which I have committed) as the de-facto plugin of choice. Our previous forms, while on MVC Beta, had the following HTML generated:

<input type="text" name="PostalCode" id="PostalCode" />

Since we have upgraded to MVC version 1.0, our HTML is now generated like this:

<input type="text" name="Address.PostalCode" id="Address.PostalCode" />

This introduced a problem, at least temporarily, for the validation plug-in. Whereas the property of the rules and messages was simply “PostalCode” before, it now must be “Address.PostalCode”, which causes a syntax error.

rules: {
    Address.PostalCode: { required: true; digits: true; length: 5; }

The beauty of this excellent language is that there is probably a way to handle this. There is a super simple solution, which took me one trial and no errors to figure out:

rules: {
    'Address.PostalCode': { required: true; digits: true; length: 5; }

This was a good reminder to me that JavaScript isn’t bad, the DOM is and that you can do pretty much anything in JavaScript.

Also, you can find this buried in the documentation.

Iowa Code Camp Wants You to Speak