You cannot validate email addresses using regular expressions.
Use this attribute instead:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class EmailAddressAttribute : DataTypeAttribute {
public EmailAddressAttribute() : base(DataType.EmailAddress) { ErrorMessage = "Please enter a valid email address"; }
public override bool IsValid(object value) {
if (value == null) return true;
MailAddress address;
try {
address = new MailAddress(value.ToString());
} catch (FormatException) { return false; }
return address.Host.IndexOf('.') > 0;
}
}
If you want to check on the client side for ASP.Net MVC, use this adapter:
public class EmailAddressValidator : DataAnnotationsModelValidator<EmailAddressAttribute> {
public EmailAddressValidator(ModelMetadata metadata, ControllerContext context, EmailAddressAttribute attribute) : base(metadata, context, attribute) { }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
yield return new ModelClientValidationRegexRule(Attribute.ErrorMessage,
@".+@.+\..+"); //Feel free to use a bigger regex
}
}
And register it as follows:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAddressAttribute), typeof(EmailAddressValidator));
SLaks source
share