Skip to content

Instantly share code, notes, and snippets.

@nootn
Last active August 29, 2015 13:58
Show Gist options
  • Save nootn/10091198 to your computer and use it in GitHub Desktop.
Save nootn/10091198 to your computer and use it in GitHub Desktop.
Yet another email validation mechanism
public class Model : IValidatableObject
{
[Display(Name = "Send to (email)")]
[Required(ErrorMessage = "'{0}' must be supplied")]
[RegularExpression(@".+\@.", ErrorMessage = "{0}' must be an email address")]
public override string ToEmailAddress { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
ValidationResult emailInvalidError = null;
try
{
var email = new System.Net.Mail.MailAddress(ToEmailAddress);
Debug.WriteLine("Email validated with host '{0}'", email.Host);
}
catch (FormatException)
{
emailInvalidError = new ValidationResult("'Send to' must be a valid email address", new[] { "ToEmailAddress" });
}
if (emailInvalidError != null)
{
yield return emailInvalidError;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment