Validating an email address

Having 100% RFC-compliant email validation is hard, see this answer for details. In .NET two relatively straightforward ways is to use MailAddress

try {
    new MailAddress("invalid_email");
} catch (FormatException) {
    // invalid
}
// TODO: ask MS to implement MailAddress.TryParse to avoid exception

Or more strict Regex-based approach from MSDN (handles IDN and Regex parsing timeout for .NET 4.5):

// NET 4.0
Boolean mappingInvalid = false;
emailString = Regex.Replace(emailString, @"(@)(.+)$", match => {
    String domainName = match.Groups[2].Value;
    try {
        domainName = new IdnMapping().GetAscii(domainName);
    } catch (ArgumentException) {
        mappingInvalid = true;
    }
    return match.Groups[1].Value + domainName;
});
if (mappingInvalid) {
    return false;
}
return Regex.IsMatch(emailString,
        @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
        @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
        RegexOptions.IgnoreCase);

You could just split the email string on the comma and validate each email address using a simple (or huge) email regex. Or, try creating a MailAddress object; it supports some basic validation of the address too.


This is code we have on production (even added a comma for you). Normally you shouldn't use try/catch for validation, but it works well here. I believe it's better than trying to recode the validator.

string[] allToAddresses = to.Split(";,".ToCharArray(),
                                 StringSplitOptions.RemoveEmptyEntries)
foreach (string toAddress in allToAddresses)
{
    try
    {
        message.To.Add(toAddress);
    }
    catch (FormatException)
    {
        //do nothing, ill-formed address. 
    }
}

Currently we are using following function and it is working quite well for us :)

public static bool IsValidEmail(string email)
{
    // source: http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx
    Regex rx = new Regex(
    @"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
    return rx.IsMatch(email);
}

Please use this:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Tags:

C#

.Net

Email