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.

About Chris Missal

I'm a software developer living in Cedar Rapids, Iowa. I help out with IowaCodeCamp, IowaJS, and CRineta. I have a passion for learning "new things", focusing primarily in web development.
This entry was posted in ASP.NET MVC, jQuery. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://trephine.org Balaji

    Great article! Thanks for taking the time to explain jQuery Validation and ASP.NET MVC Forms. I’ve been thinking about similar topics lately, and it’s good to see that I’m not alone. What do you think about JavaScriptMVC – Include?

  • http://www.lostechies.com/members/chrismissal/default.aspx Chris Missal

    @Balaji

    I actually heard today that there is going to be jQuery validation baked into ASP.NET MVC 2.0!