Regex Email validation

TLD’s like .museum aren’t matched this way, and there are a few other long TLD’s. Also, you can validate email addresses using the MailAddress class as Microsoft explains here in a note:

Instead of using a regular expression to validate an email address,
you can use the System.Net.Mail.MailAddress class. To determine
whether an email address is valid, pass the email address to the
MailAddress.MailAddress(String) class constructor.

public bool IsValid(string emailaddress)
{
    try
    {
        MailAddress m = new MailAddress(emailaddress);

        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

This saves you a lot af headaches because you don’t have to write (or try to understand someone else’s) regex.

EDIT: For those who are allergic to try/catch: In .NET 5 you can use MailAddress.TryCreate. See also https://stackoverflow.com/a/68198658, including an example how to fix .., spaces, missing .TLD, etc.

Leave a Comment