Compare Attribute in ASP.NET MVC 3

ASP.NET MVC 3 introduces a number of attributes which derive from ValidationAttribute (System.ComponentModel.DataAnnotations) having client-side validation support. One such attribute is the Compare attribute using which you can compare properties of a model for eg: ‘Email Address’ and ‘Confirm Email Address’.

Here’s an example of how to use this attribute in your application. Consider a sample Visitor class

mvccompareattribute

As you can see, the Compare attribute makes it extremely simple to compare two properties and also define a validation rule. The user is given instant feedback via the ValidationAttribute, if the email addresses do not match.

You may also want to read some more tips over here - ASP.NET MVC 3: Display Empty Data Text in WebGrid and ASP.NET MVC: Use CSS on Html.ActionLink






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

Unknown said...

Suprotim,

This is a good start. However, for MVP post to appear on Microsoft's Spotlight page I'd expect more "meat". For example, Compare Attribute allows not only the trivial "match" comparison but also "greater than" with virtual IsValid method. There are many very good posts (using Start Date and End Date as typical example) that explain this feature!

Good luck!

Suprotim Agarwal said...

That's a good use case Felix. My intention while this post was to introduce the most common use cases - like comparing email address or the Password/ ConfirmPassword fields. Thanks for letting me know that this post hit the spotlight page ;)

Stacey said...

I will agree. This is a good post, but when I saw it I got excited because I thought it would dissect how the thing actually works (since even in the MVC source code it's a bit ambiguous).

A++ for showing something useful.

Mike Bethany said...

Good info, thanks. It should be noted that while Compare may derive from System.ComponentModel.DataAnnotations you need to import the System.Web.Mvc namespace to actually see it.