Updated on

To validate an email address in C#, we can parse it with MailAddress.TryCreate(), check it with the EmailAddressAttribute, match it against a regular expression, or use FluentValidation’s EmailAddress() rule. Each one lets different inputs through, and none of them proves that the mailbox exists.

Validating an email address is a common task in the routine of a software developer, especially when we build applications that deal with users’ data. We’ll start with the built-in classes and then move on to regex and FluentValidation.

To download the source code for this article, you can visit our GitHub repository.

We have a lot to cover, so let’s start.

What Makes an Email Address Valid?

A valid email address consists of two sections. The first represents the username and the second part represents the domain. These sections are separated by the @ symbol.

Both sections accept letters (from a to z), digits (from 0 to 9), periods (.), and hyphens (-). In addition, the first part also might include special characters such as: !#$%&’*+-/=?^_`{|}~. Newer standards also allow letters outside the English alphabet, so ć[email protected] is a valid address too.

In practice, the second section almost always has at least one period. The address syntax itself doesn’t require one, though, so code@maze is a valid address, and most of the checks in this article accept it. What we cannot do is use two periods next to each other, or a period as the first or the last character in either section, unless the first part is in quotes.

Validate an Email Address With the MailAddress Class

Now that we understand the composition of a valid email address, let’s create a new console application using the Visual Studio wizard or the dotnet new console command.

For our first approach, we will utilize the built-in MailAddress class to validate an email address.

To do so, let’s create an EmailValidator class and add our first method to it:

using System.Net.Mail;

public bool ValidateUsingMailAddress(string emailAddress)
{
    try
    {
        var email = new MailAddress(emailAddress);
        return email.Address == emailAddress.Trim();
    }
    catch
    {
        return false;
    }
}

This method receives a string (emailAddress) variable as an input parameter to check whether this email address is valid or not.

The MailAddress class might throw three different exceptions: ArgumentNullException, ArgumentException, or FormatException.

If we catch any of these exceptions, we can assume that our email address is invalid and we return false. On the other hand, if the Address property from the email object is equal to the emailAddress we received as an input parameter, we assume that this is a valid email address.

We compare the Address property with the input because MailAddress also understands the display-name format we see in email clients. It doesn’t throw for code [email protected]. Instead, it reads code as the display name and [email protected] as the address, and the comparison is what catches it.

Since .NET 5, we can skip the try-catch block too. The MailAddress.TryCreate() method returns false instead of throwing, so let’s add a second method to our EmailValidator class:

public bool ValidateUsingMailAddressTryCreate(string emailAddress)
{
    return MailAddress.TryCreate(emailAddress, out var email)
        && email.Address == emailAddress.Trim();
}

It gives the same answers as our first method for every input in this article, and an invalid address no longer goes through an exception. When we need to validate an email without a regex, this is the method we reach for first.

It is important to say that the MailAddress class makes a basic level of validation for email format. That said, we should not solely depend on it to validate the users’ email addresses.

That leads us to the next approach.

Validate an Email Address Using EmailAddressAttribute

Let’s check how we can validate an email address using the EmailAddressAttribute class:

using System.ComponentModel.DataAnnotations;

public bool ValidateUsingEmailAddressAttribute(string emailAddress)
{
    var emailValidation = new EmailAddressAttribute();

    return emailValidation.IsValid(emailAddress);
}

Here, our method receives a string representing the emailAddress as an input parameter and returns a boolean indicating if the email is valid or not. 

Initially, we create a new instance of the EmailAddressAttribute object. Then, we return a call to the IsValid() method that is going to evaluate true or false.

The EmailAddressAttribute class validates email addresses differently depending on the version of .NET we are using.

In .NET Framework 4.x, it uses a regular expression to validate the email address. In .NET Core and every .NET version since, it only checks that the string contains exactly one @ symbol and that this symbol is neither the first nor the last character. Current versions also reject a string with a line break in it.

With that in mind, let’s run this method with an array of invalid email addresses:

code.maze.com          // false
code@[email protected] // false
[email protected]         // true

On .NET 10, the EmailAddressAttribute checks for a single ‘@’ symbol that is not at the beginning or end of the string. Therefore, the email address [email protected] is valid according to this validation method.

The attribute also returns true for null. It leaves missing values to the [Required] attribute, which is why a model property usually carries both, as in [Required, EmailAddress]. If we use it on an API model, our article on ModelState validation in ASP.NET Core shows where those attributes run.

Use Regex to Validate an Email Address in C#

Regular expressions are a powerful tool for pattern matching within strings. When we are validating an email address, we can use a regular expression to match the local and domain parts of the email address against their respective patterns.

Let’s check how to use Regex to validate an email address:

using System.Text.RegularExpressions;

public bool ValidateUsingRegex(string emailAddress)
{
    var pattern = @"^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$";
            
    var regex = new Regex(pattern);

    return regex.IsMatch(emailAddress);
}

As the first step, we create a string variable (pattern) with the pattern to use in the regex validation.

Then, we instantiate a new Regex class, passing the pattern as a constructor parameter.

Finally, we use the IsMatch() method from the regex instance and pass, as a parameter, the email address we want to validate.

If the regex validates it as a valid email address, we return true. Otherwise, we return false.

The pattern has two parts around the @. The local part is one or more allowed characters, optionally followed by more groups that each start with a single period. That’s how it rejects [email protected] and [email protected]. The domain part is letters, digits and hyphens, separated by single periods.

Notice that the hyphen sits at the very end of the first character class. At the end, it means a literal hyphen. Put it in the middle, as in +-/, and it creates a range from + to / instead, which also lets a comma through, so co,[email protected] would pass.

Since .NET 7, we can also let the regex source generator build this regex at compile time, instead of parsing the pattern every time the method runs. Let’s move the pattern into a constant and add a generated version:

public partial class EmailValidator
{
    private const string EmailPattern =
        @"^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$";

    [GeneratedRegex(EmailPattern)]
    private static partial Regex EmailRegex();

    public bool ValidateUsingGeneratedRegex(string emailAddress)
    {
        return EmailRegex().IsMatch(emailAddress);
    }
}

The class has to be partial so the generator can add the implementation, and the pattern itself doesn’t change. Our article on source-generated regex explains what the generator produces and what it saves.

Keep in mind that this pattern only knows ASCII letters. A valid international address such as ć[email protected] fails it, and so does a quoted local part like "code maze"@maze.com.

Email Validation With FluentValidation

Another approach we can use to validate email addresses is using the FluentValidation NuGet package.

First, let’s use Manage NuGet Package or the Package Manager Console to install the FluentValidation package:

Install-Package FluentValidation

Or, from the command line: dotnet add package FluentValidation

Then, let’s set up our validation:

using FluentValidation;

public class EmailFluentValidator : AbstractValidator<string>
{
    public EmailFluentValidator()
    {
        RuleFor(email => email)
            .EmailAddress();
    }
}

The EmailFluentValidator class inherits from the AbstractValidator class. It gives the EmailFluentValidator class the ability to use the RuleFor() method to validate its properties.

The subsequent step consists of using the RuleFor() method inside the EmailFluentValidator constructor.

In this case, we set up the RuleFor() method to validate if the string is a valid email address (using the EmailAddress() method).

Let’s use the same invalid emails string array we used in the EmailAddressAttribute section against this method to check its behavior:

code.maze.com          // false
code@[email protected] // false
[email protected]         // true

After inspecting the result, we can see that this validation considers the [email protected] a valid email address.

When we don’t pass any parameter to the EmailAddress() method, it runs the same @ check as the most recent versions of the EmailAddressAttribute class, though it doesn’t reject line breaks the way the attribute does.

That’s by design. The FluentValidation documentation quotes the .NET team’s reasoning: “The check is intentionally naive because doing something infallible is very hard.”

Alternatively, we can pass the EmailValidationMode.Net4xRegex enum to validate it using regex:

using FluentValidation;
using FluentValidation.Validators;

public class EmailFluentRegexValidator : AbstractValidator<string>
{
    public EmailFluentRegexValidator()
    {
        RuleFor(email => email)
            .EmailAddress(EmailValidationMode.Net4xRegex);
    }
}

Now, the validator considers the email address ([email protected]) invalid.

This mode still works in FluentValidation 12, but it is marked obsolete, so the compiler warns us when we use it:

warning CS0618: 'EmailValidationMode.Net4xRegex' is obsolete: 'Regex-based email validation is not recommended and is no longer supported.'

We’d keep it only for code that already depends on it. It also rejects code@maze, which every other check in this article accepts.

How Should We Check if an Email Is Valid in C#?

For a format check, MailAddress.TryCreate() is the best default. It ships with .NET and doesn’t throw, and it rejected every broken input in our sample: a missing @, two @ signs, a period right after the @, a comma, and two periods in a row. We still compare its Address property with the input, because the parser reads code [email protected] as a display name plus an address.

The EmailAddressAttribute and FluentValidation’s default EmailAddress() rule check much less. Both want exactly one @ that is neither first nor last, and only the attribute also rejects line breaks. That’s fine for a quick form check, as long as something stricter runs behind it.

A regex is exactly as strict as the pattern we write. Ours rejects valid international addresses.

None of these checks tells us whether the mailbox exists. Only a confirmation email does that, so we treat format validation as a typo filter.

Here’s what each approach returns for the same inputs on .NET 10. Every row is a test case in the sample’s ValidatorComparisonTests class, so we can rerun it on any later .NET version.

InputOur MailAddress methodsEmailAddressAttribute / FluentValidation defaultOur regexFluentValidation Net4xRegex
[email protected]ValidValidValidValid
code@mazeValidValidValidInvalid
[email protected]InvalidValidInvalidInvalid
co,[email protected]InvalidValidInvalidInvalid
[email protected]InvalidValidInvalidInvalid
code [email protected]InvalidValidInvalidInvalid
Code Maze <[email protected]>InvalidValidInvalidInvalid
"code maze"@maze.comValidValidInvalidValid
ć[email protected]ValidValidInvalidValid

The attribute column says Valid on every row, including the five rows that all three stricter checks reject.

Conclusion

In this article, we have learned the basics of email composition. Also, we explored some different approaches to validating an email address and its weaknesses.

We don’t have a single perfect approach, and choosing the right methods depends on specific requirements such as the level of strictness, complexity, and customization. When we want low complexity, MailAddress.TryCreate() or the EmailAddressAttribute are good options. However, if we already validate our models with FluentValidation, its EmailAddress() rule keeps the email check next to the rest of our rules.

In the last case, if we need a high level of strictness, a regular expression lets us define specific rules for validating the format of an email address. On the other hand, it is more complex, harder to maintain than other approaches, and easy to get wrong: one misplaced hyphen in a character class lets a comma through.

Whichever approach we pick, the only proof that an address works is a message that reaches it. If we need to send that confirmation email, our article on sending email in ASP.NET Core shows how.

Now that we know the pros and cons of each approach, it is up to us to decide which one to use in our projects.

Tested with .NET 10.0.10, FluentValidation 12.2.0 and xUnit 2.9.3.