Using DataAnnotations to compare two model properties

Scott picture Scott · Feb 8, 2011 · Viewed 67.8k times · Source

How would I go about writing a custom ValidationAttribute that compares two fields? This is the common "enter password", "confirm password" scenario. I need to be sure the two fields are equal and to keep things consistent, I want to implement the validation via DataAnnotations.

So in pseudo-code, I'm looking for a way to implement something like the following:

public class SignUpModel
{
    [Required]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [Display(Name = "Re-type Password")]
    [Compare(CompareField = Password, ErrorMessage = "Passwords do not match")]
    public string PasswordConfirm { get; set; }
}

public class CompareAttribute : ValidationAttribute
{
    public CompareAttribute(object propertyToCompare)
    {
        // ??
    }

    public override bool IsValid(object value)
    {
        // ??
    }
}

So the question is, how do I code the [Compare] ValidationAttribute?

Answer

Janx from Venezuela picture Janx from Venezuela · Jan 12, 2012

Make sure that your project references system.web.mvc v3.xxxxx.

Then your code should be something like this:

using System.Web.Mvc;

. . . .

[Required(ErrorMessage = "This field is required.")]    
public string NewPassword { get; set; }

[Required(ErrorMessage = "This field is required.")]
[Compare(nameof(NewPassword), ErrorMessage = "Passwords don't match.")]
public string RepeatPassword { get; set; }