You should not validate email addresses using regular expressions.
Instead, use this attribute:
[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; //Email address domain names do not need a ., but in practice, they do.
}
}
If you want client-side validation 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 like this:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAddressAttribute), typeof(EmailAddressValidator));