I've been playing around data annotations in MVC2 and am curious if there is an annotation to compare 2 properties (ie. password, confirm password)?
Asked
Active
Viewed 2.1k times
17
-
1See http://stackoverflow.com/questions/2450198/how-to-validate-two-properties-with-asp-net-mvc-2 – Çağdaş Tekin Mar 15 '10 at 22:49
4 Answers
42
If you are using ASP.Net MVC 3, you can use System.Web.Mvc.CompareAttribute
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string PasswordConfirm { get; set; }

Greg B
- 14,597
- 18
- 87
- 141

Cillié Malan
- 864
- 11
- 13
-
5why is this in system.web.mvc instead of dataAnnotations? Shouldn't have to reference system.web.mvc in my model project. How annoying. – Patrick Lee Scott Sep 29 '11 at 19:49
-
11
6
Here you go: http://www.dotnetguy.co.uk/post/2010/01/09/Property-Matching-With-Data-Annotations.aspx
Edit:
New link: http://www.dotnetguy.co.uk/post/2010/01/09/property-matching-with-data-annotations/

Community
- 1
- 1

Dustin Laine
- 37,935
- 10
- 86
- 125
2
System.Web.Mvc.CompareAttribute has been deprecated.
I was able to modify to work like this:
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }

Mitch
- 85
- 2
- 11
0
There's not one built in, however, you can make your own. See this link, which shows the "PropertiesMustMatchAttribute" that does just what you're looking for.

David Morton
- 16,338
- 3
- 63
- 73