How to create a Must Not Match attribute for email

2019-07-19 19:58发布

问题:

i am using data annotation to validate my properties, below are the properties for my page

public string YourEmail{get;set;}
public string AnotherEmail{get;set;}

my requirement is that both email id should not be same

please suggest what should i use from data annotation to solve this issue

thanks,

回答1:

You have to implement IValidatableObject interface in your model and add method Validate in your model.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
      List<ValidationResult> validationResults = new List<ValidationResult>();

      if (string.Equals(this.Email1,this.Email2,StringComparison.OrdinalIgnoreCase))
      {
          validationResults.Add(new ValidationResult(ErrorMessage.EmailError, new string[] { "Email ID" }));
      }

      return validationResults;
}

Or You can create the custom dataannotation as per your requirement. Please refer below URL.

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute%28v=vs.95%29.aspx