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.

Share:
40,355
Mark
Author by

Mark

Updated on August 11, 2022

Comments

  • Mark
    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
    kyle over 6 years
    in .net core it's [Compare("EmailAddress", ErrorMessage = "Emails mismatch")]
  • Łukasƨ Fronczyk
    Łukasƨ Fronczyk almost 5 years
    Use [Compare(nameof(EmailAddress), ErrorMessage = "Emails mismatch")], so in case of future change of the action name you won't finish with hidden bug.
  • dove
    dove almost 5 years
    good call @ŁukasƨFronczyk, I've updated the answer with this.
  • paraJdox1
    paraJdox1 about 2 years
    also add [NotMapped] above VerifiedEmailAddress property, so that it doesn't become a column in your database. (so VerifiedEmailAddress doesn't map to a column)
  • dove
    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
    paraJdox1 about 2 years
    @dove I didn't notice that "ViewModel", but just incase my comment can help someone as well :))