DataAnnotation to compare two properties
40,355
Solution 1
Use the CompareAttribute
public string EmailAddress {get; set;}
[Compare(nameof(EmailAddress), ErrorMessage = "Emails mismatch")]
public string VerifiedEmailAddress { get; set; }
Solution 2
As one possibe option self-validation:
Implement an interface IValidatableObject with method Validate, where you can put your validation code.
public class TestModel : IValidatableObject
{
public string Email{ get; set; }
public string ConfirmEmail { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Email != ConfirmEmail)
{
yield return new ValidationResult("Emails mismatch", new [] { "ConfirmEmail" });
}
}
}
Please notice: this is only server-side validation.
Author by
Mark
Updated on August 11, 2022Comments
-
Mark over 1 year
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?
-
kyle over 6 yearsin .net core it's [Compare("EmailAddress", ErrorMessage = "Emails mismatch")]
-
Łukasƨ Fronczyk almost 5 yearsUse
[Compare(nameof(EmailAddress), ErrorMessage = "Emails mismatch")]
, so in case of future change of the action name you won't finish with hidden bug. -
dove almost 5 yearsgood call @ŁukasƨFronczyk, I've updated the answer with this.
-
paraJdox1 about 2 yearsalso add
[NotMapped]
aboveVerifiedEmailAddress
property, so that it doesn't become a column in your database. (soVerifiedEmailAddress
doesn't map to a column) -
dove about 2 years@JDDalmao this is a good point for domain models but I'm thinking as OP refers to ViewModel that this is not a persistence model but purely a front-end one that then gets mapped back to a domain model.
-
paraJdox1 about 2 years@dove I didn't notice that "ViewModel", but just incase my comment can help someone as well :))