Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataAnnotation to compare two properties

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?

like image 822
Mark Avatar asked Feb 21 '14 10:02

Mark


2 Answers

Use the CompareAttribute

public string EmailAddress {get; set;}

[Compare(nameof(EmailAddress), ErrorMessage = "Emails mismatch")]
public string VerifiedEmailAddress { get; set; }
like image 84
dove Avatar answered Oct 26 '22 05:10

dove


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.

like image 16
Andrei Avatar answered Oct 26 '22 05:10

Andrei