There are many ways to validate if an e-mail address is right, and many wrong ways. The biggest wrong way is using a Regular expression, why? They are complex and there is not one that resolves this issue, you will always get an invalid e-mail address that passes through okay.
So what can we do? Why not use something that already works, something that someone else maintains, something we already have?
Let’s take a look at the System.Net.Mail name space, it has MailAddress, and if you add a string that is an invalid e-mail address it fails eg:
new MailAddress("invalidemailaddress");
This causes an exception to be thrown.
This mean you can use a single line of code to see if an e-mail is valid or not.
Let’s make it more practical and generate a ValidationAttribute that validates an email address for any given field in a model, what we are after doing is something like this:
public class UserModel { [Required] public string name { get; set; } [Email] public string email { get; set; } }
To does this we just need to create an email attribute:
public class EmailAttribute : ValidationAttribute { protected override ValidationResult IsValid (object value, ValidationContext validationContext) { if (string.IsNullOrWhiteSpace(value?.ToString())) return ValidationResult.Success; try { new MailAddress(value.ToString()); } catch (Exception) { return new ValidationResult("Please provide a valid email address."); } return ValidationResult.Success; } }
So simple when you know how to do it.