The World’s Leading Microsoft .NET Magazine
   
 
The .NET Addict's Blog

My Top Tags

                                                           

My RSS Feeds








I heart FeedBurner

Latest Diggs - Programming

Computers Blogs - Blog Top Sites

Site Hits

Total: 4,882,895
since: 19 Jan 2005

Client-Side Validation with jQuery, DataAnnotations, MVC 2, and VS2010 Beta 2

posted Mon 26 Oct 09

Anytime a feature of a framework gives me something for free that I don't need to manually implement I'm a happy camper. One such feature of ASP.NET MVC 2 is jQuery client-side validation. The reason I like this is that unlike other jQuery frameworks, where you have to write the jQuery yourself - you don't need to do that with MVC 2.

Instead of having to maintain simple validation logic in two places (your business classes and your jQuery code), you can now use the Data Annotations attributes and metadata "buddy" classes to decorate your models. Those decorated models will automatically generate the appropriate jQuery code to enforce all of your validation rules on the client side before the form is ever submitted. Let's see how this works.

First, we need a model class. Let's do something simple like Customer:

public partial class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
}

This is great. I love the fact that it doesn't look ugly and view developers can look at it and immediately know what fields are available and they don't need to sift through a pile of persistence garbage or validation logic. You might have noticed that I've made this class partial. The reason I'm doing this is because I'm going to create another file called Customer.metadata.cs. There are other samples on the web that don't do this, but I like cleanly separating the definition of my model from the validation logic for that model. Here's a look at my Customer.metadata.cs file:

[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
    class CustomerMetaData
    {
        [Required(ErrorMessage="You must supply a name for a customer.")]
        [StringLength(50, ErrorMessage = "A customer name cannot exceed 50 characters.")]
        public string Name { get; set; }
    }
}

What I've done here is used a metadata "buddy class" (that's what posts from Scott Guthrie and Scott Hanselman have been calling them, so I'm sticking with convention here). This buddy class is a placeholder for all my validation logic attributes and the runtime will then merge all this stuff onto the actual model. MVC 2 will then examine the model and , with a few lines of code in the view, generate the appropriate jQuery client-side validation logic.

In your view code, add the following 3 script declarations:

<script type="text/javascript" src="../../Scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcJQueryValidation.js"></script>

Finally, somewhere before the start of your form tag, add the following markup to the view code:

<% Html.EnableClientValidation(); %> 

This will invoke the code that reads through the strongly typed model for your view, figures out all of the validation logic that applies, and generates the appropriate jQuery code.

While you could write your own jQuery validation code if you felt like it, using data annotations and MVC 2, you no longer have to maintain your validation logic in two places. The attributes apply to a single view model and all you have to do is change one of those attributes and the generated jQuery code will change as well. This is a huge timesaver and promises to dramatically increase overall productivity of developers building large-scale MVC 2 applications, especially LOB apps with lots of data entry forms.

 

tags:                

links: digg this    del.icio.us    technorati    reddit

AddThis Social Bookmark Button




1. Simon Timms left...
Tue 24 Nov 09 10:47 am

This was most helpful, Haacked's blog article didn't mention buddy classes and I have become addicted to them thanks to xVal


2. JJ left...
Thu 14 Jan 10 4:27 am :: http://www.jamie-jones.co.uk

Is it possible to use the Annotations to validate server side too so you don't need separate code?

Just moved one of my projects to mvc 2 so I'll be giving this a go, cheers.


3. Kevin Hoffman left...
Thu 14 Jan 10 8:28 am

If you use the annotations, the annotations are the -only- source of your validation information and it will do the client-side (jQuery) validations where appropriate, and do the custom validations (the ones that can't be translated into jQuery) on the server - the user will never know which one was client and which one was server- it'll look the same.


Tag Related Posts

Html.JqGrid - Cleaning up your jqGrid Code

Tue 22 Dec 09 8:46 P GMT-05
tags:              

Get Your Red Hot VS2010 Beta 2!

Mon 19 Oct 09 8:43 P GMT-05
tags:      

How to Build your First Azure-Powered MVC App

Tue 29 Sep 09 2:16 P GMT-05
tags:        

ViewState is the Froo-It of the Dev-Il

Wed 23 Sep 09 3:09 P GMT-05
tags:      

Fix for Minor Bug in ASP.NET MVC New Project Template

Mon 04 May 09 2:48 A GMT-05
tags:      

Microsoft's Lofty Direction

Sun 05 Oct 08 2:30 P GMT-05

NYC SharePoint Developer Needed

Mon 12 May 08 12:09 P GMT-05

Scott Guthrie Updates the ASP.NET MVC Roadmap

Wed 13 Feb 08 3:49 P GMT-05
tags:    

Volta is to Ajax what Tums is to my Stomach

Wed 30 Jan 08 4:11 P GMT-05

ASP.NET 3.5 Extensions Preview Released

Mon 10 Dec 07 2:10 P GMT-05

Microsoft unveils an MVC framework for ASP.NET

Mon 08 Oct 07 12:58 P GMT-05
tags:      

Exploring the MVC Pattern in WPF

Tue 10 Apr 07 12:51 P GMT-05
tags:                      

ASP.NET Ajax v1.0 Beta

Fri 27 Oct 06 6:17 P GMT-05
tags:      

ASP.NET vs Ruby on Rails : Round 2 (Agility)

Thu 05 Oct 06 11:02 A GMT-05
tags:                      

ASP.NET vs Ruby on Rails : Round 1

Wed 04 Oct 06 1:37 P GMT-05
tags: