Email Validation in C#: Regex, MailAddress and Their Limits

A regular expression can tell you that a string has the shape of an email address. It cannot tell you that the address is valid, let alone that it exists. The grammar in RFC 5322 allows quoted local parts, comments and IP-address domains, and the patterns that try to cover all of it are thousands of characters long and still disagree with real mail servers. Treat validation as a sanity check that catches typos, then confirm the address by sending a message to it.

With that settled, here are two reasonable checks.

Option 1: MailAddress.TryCreate

System.Net.Mail.MailAddress has a parser built in. TryCreate (available since .NET 5) returns false instead of throwing:

using System.Net.Mail;

string[] inputs =
[
    "admin@csharpexamples.com",
    "john.smith+news@example.co.uk",
    "Admin <admin@csharpexamples.com>",
    "admin@@csharpexamples.com",
    "admin",
];

foreach (string input in inputs)
{
    Console.WriteLine($"{input,-35} {IsValidEmail(input)}");
}

static bool IsValidEmail(string input) =>
    MailAddress.TryCreate(input, out MailAddress? address)
    && address.Address == input;

Output:

admin@csharpexamples.com            True
john.smith+news@example.co.uk       True
Admin <admin@csharpexamples.com>    False
admin@@csharpexamples.com           False
admin                               False

The address.Address == input comparison matters. MailAddress also accepts the display-name form Admin <admin@csharpexamples.com> and returns only the address part, which is correct for an email header but not what you want from a sign-up form field. Comparing the parsed address with the input rejects anything extra, including surrounding whitespace, so call Trim() on user input first.

Be aware of what it lets through: admin@localhost passes, because a domain without a dot is legal. If you only accept internet addresses, add a check that the host contains a dot.

Option 2: a simple regex

If you prefer a pattern, keep it deliberately loose: something without spaces, one @, something without spaces, a dot, and something without spaces.

using System.Text.RegularExpressions;

Console.WriteLine(EmailValidator.LooksLikeEmail("admin@csharpexamples.com"));   // True
Console.WriteLine(EmailValidator.LooksLikeEmail("admin@csharpexamples.com\n")); // False
Console.WriteLine(EmailValidator.LooksLikeEmail("admin@csharpexamples"));       // False

static partial class EmailValidator
{
    [GeneratedRegex(@"^[^@\s]+@[^@\s]+\.[^@\s]+\z")]
    private static partial Regex EmailPattern();

    public static bool LooksLikeEmail(string input) => EmailPattern().IsMatch(input);
}

[GeneratedRegex] (.NET 7 and later) generates the matching code at build time, so there is no regex parsing at runtime and a typo in the pattern fails the build. On older frameworks use a static readonly Regex field instead.

The pattern ends with \z, not $. In .NET, $ also matches just before a trailing newline, so a $-terminated pattern accepts "admin@csharpexamples.com\n". That newline is exactly the kind of thing that later breaks an SMTP header.

What was wrong with the old pattern

The original version of this page used this:

^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$

It looks thorough, and it rejects real addresses:

  • john+news@gmail.com fails, because + is not allowed in the local part. Gmail and many other providers support plus addressing, and people use it to filter sign-up mail.
  • info@studio.photography fails, because the top-level domain is limited to 9 letters. Many current TLDs are longer.
  • o'brien@example.com fails, because the apostrophe is not allowed either, although it is legal and appears in real names.

It also has a nested quantifier, ([-\.\w]*[0-9a-zA-Z])*, which can backtrack exponentially on a long input that almost matches. Running that against form input without a match timeout invites a denial of service. A strict pattern costs you real customers and buys almost nothing, because typo@gmial.com passes every pattern ever written.

ASP.NET Core and DataAnnotations

If you validate a model, the [EmailAddress] attribute from System.ComponentModel.DataAnnotations is enough. In current .NET it does not use a regex at all: it checks for exactly one @ that is neither the first nor the last character. That is in line with the advice above.

using System.ComponentModel.DataAnnotations;

public class SignUpModel
{
    [Required, EmailAddress]
    public string Email { get; set; } = "";
}

Whichever check you choose, store the address as entered (trimmed) and send a confirmation link before you trust it. That link is the only real validation there is.

Related examples

Leave a Comment