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


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

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


4 Responses to "Compare Attribute in ASP.NET MVC 3"
  1. Felix said...
    March 18, 2011 at 11:01 AM


    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!

  2. Suprotim Agarwal said...
    March 18, 2011 at 5:51 PM

    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 ;)

  3. Stacey said...
    March 22, 2011 at 5:28 AM

    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.

  4. Mike Bethany said...
    July 10, 2012 at 10:16 AM

    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.


Copyright © 2009-2014 All Rights Reserved for by Suprotim Agarwal | Terms and Conditions