DataAnnotation to compare two properties

Mark picture Mark · Feb 21, 2014 · Viewed 37.2k times · Source

Is there any way of using data annotations to compare two form field (eg. to confirm an email address) are the same, before allowing the form to be posted?

eg. can the regular expression data annotation use the match function to reference another property in a ViewModel?

Answer

dove picture dove · Feb 21, 2014

Use the CompareAttribute

public string EmailAddress {get; set;}

[Compare(nameof(EmailAddress), ErrorMessage = "Emails mismatch")]
public string VerifiedEmailAddress { get; set; }