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.

Related:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Chris Missal

Oh hey, I'm a Senior Consultant for Headspring in Austin, TX. I've been working in software professionally since 2006 and I really, really love it. I'm mostly in the Microsoft world, but enjoy building computer things of all sorts (to be vague). When I'm not slinging code, I'm probably out and about slinging discs, bowling balls, or good beer with great friends.
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!