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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…