EmailAddressAttribute
is a sealed class,we can't use EmailAddressAttribute
to create custom validation class derived from it, but you can extend from ValidationAttribute
when creating specific validation rules to email address field instead using default one.
public class CustomEmailAddressAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
Regex rgx = new Regex(@"[a-z0-9._%+-]+@mit.edu");
if(!rgx.IsMatch(value.ToString()))
{
return new ValidationResult(GetErrorMessage());
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Please enter a valid email which ends with @mit.edu";
}
}
Model:
[CustomEmailAddress]
public string StudentEmail { get; set; }
Or you could directly use regex validation, you could use below validation simply:
[RegularExpression(@"[a-z0-9._%+-]+@mit.edu", ErrorMessage = "Please enter a valid email which ends with @mit.edu")]
public string StudentEmail { get; set; }