Guides
Last updated
August 4, 2023

Simple guide to Email Validation in C#

Emma Jagger

Table of Contents:

Get your free
Email Validation
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

This guide will explain some of the most popular methods of validating emails in C#. Use these methods to ensure the email addresses in your application are valid, usable, and without error.

How to validate email address in C#

First of all, what is email address validation and what is the best way to validate an email? Email address validation is making sure an email address is correctly formatted and usable. 

For example, the email address abcdefg@hijklm.nop is correctly formatted as it contains a ‘.’ and ‘@’ character. However, it can not be considered usable as the domain is not valid. 

In this guide we’ll cover the most popular ways to validate emails in C# including the following:

  • Validating email addresses with System.Net.Mail.MailAddress
  • Validating email addresses with a regular expression or Regex, specifically System.Text.RegularExpressions
  • Validation through data annotations, specifically through the System.ComponentModel.DataAnnotations.EmailAddressAttribute class.

We will demonstrate each of these methods, clearly explaining each step and showing sample code that checks for a valid email address. Let’s get started with the first way to validate an email address in C#. 

Let’s send your first free
Email Validation
call
See why the best developers build on Abstract
Get your free api

Validate email address with System.Net.Mail.MailAddress

The MainAddress class in C# is designed to handle email addresses in your code. From the official Microsoft documentation, a MailAddress includes:

  • A user name;
  • a hostname;
  • and optionally, a DisplayName. The DisplayName can contain non-ASCII characters if you encode them.

If you would like to follow along with the code used in this tutorial, you can use the free version of Visual Studio Code! Take a look at the example MailAddress declaration below:



MailAddress mail = new MailAddress("johndoe123@email.com", "John Doe");

This MailAddress can be broken down into the following parts:

  • The user name - “johndoe123”.
  • The hostname: “email.com”. This is also known as the domain part of an email.
  • The DisplayName: “John Doe”.

Now let’s look at an example of how we can use the MailAddress class to check if a string email is a valid email address. Take a look at the code below:



public static bool IsValidEmail(string email)
{
try
{
MailAddress mail = new MailAddress(email);
return true;
}
catch (Exception e)
{
return false;
}
}


If the string address is not a valid email address and doesn’t adhere to the rules of the MailAddress class, an exception will be raised and the method will return false. 

You can use this method like so:



public class Program
{
public static void Main(string [] args)
{
string input = "abcdef";
string emailInput = "abc@gmail.com";

bool validEmail = CheckValidEmailAddress(input);
Console.WriteLine("The value of validEmail is: " + validEmail);

validEmail = CheckValidEmailAddress(emailInput);
Console.WriteLine("The value of validEmail is: " + validEmail);
}
}

Executing this code will print out two lines:

  • “The value of validEmail is: false” - This is because input, or “abcdef”, is not a valid email address. 
  • “The value of validEmail is: true” - This is because emailInput, or “abc@gmail.com”, is a valid email address. 

This method is quite simple and easy to understand, making it one of the most popular methods of email address validation in C#. Obviously this is not the only way to perform email validation. Let’s move on to another method of validating emails in C#, a regular expression!

Validate email address with System.Text.RegularExpressions

Regular Expressions, or Regex, are probably the most popular way of validating mail addresses in your code. A regular expression can be used in a number of programming languages, but for this guide we’ll be looking using a regular expression to validate an email address in C#. 



public static bool RegexEmailCheck(string input)
{
// returns true if the input is a valid email
return Regex.IsMatch(input, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}

This method will compare a string with the regular expression pattern and be true or return false depending on the content of that string. The following example shows you how to invoke the method:



public class Program
{
public static void Main(string [] args)
{
string input = "abcdef";
string emailInput = "abc@gmail.com";

bool validEmail = RegexEmailCheck(input);
Console.WriteLine("The value of validEmail is: " + validEmail);

validEmail = RegexEmailCheck(emailInput);
Console.WriteLine("The value of validEmail is: " + validEmail);
}
}

As impressive as the above code seems, it is important to note that using one single regular expression to validate against all cases will be impossbile. Trying to do so will lead to complicated, overengineered expressions that are difficult to debug and maintain effectively. 

Check out this complete guide on how to validate emails with Regex if Regex sounds like the best fit for your project or web application. However, there are some limitations with Regex that are important to know. We’ll go into more detail later on about the benefits and potential limitations of using a regular expression.

Validate Email address with Data Annotations C#

Data Annotations allow you to attach attributes or rules to the variables in your code. For example, you can add an attribute such as Required to a class variable, meaning it has to have a value. Failure to provide a value for this variable will result in an error being raised. 

There is also an attribute for validation. From Microsoft’s official documentation, we can see the attribute, Validation, acts as the base class for all validator attributes. One of these validators is the EmailAddressAttribute(). Let’s look at how easy it is to implement.

Add the DataAnnotations package to your project:



using System.ComponentModel.DataAnnotations

Now add the code in the following example, which determines whether the specified value matches the pattern of a valid email address:



public static bool ValidEmailDataAnnotations(string input)
{
return new EmailAddressAttribute().IsValid(input);
}

Let’s see how use this method to check if an email address is valid:



public class Program
{
public static void Main(string [] args)
{
string input = "abcdef";
string emailInput = "abc@gmail.com";

bool validEmail = ValidEmailDataAnnotations(input);
Console.WriteLine("The value of validEmail is: " + validEmail);

validEmail = ValidEmailDataAnnotations(emailInput);
Console.WriteLine("The value of validEmail is: " + validEmail);
}
}

Try out the above code for yourself! You should see the method return false for the first input, and return true for emailInput. The program will write the results to the console. Now that we’ve covered all three methods of how to validate email addresses in C#, let’s take a closer look at the regular expression, or Regex, one of the more popular options for email validation. 

The benefits and limitations of Regex to validate email address

We mentioned earlier in this guide how Regex was the most used form of email validation, not just in C#, but probably across most programming languages. Due to this popularity, it is worth spending some extra time looking at the benefits and potential limitations using Regex to validate mail addresses in C#.

The Benefits of Regex in C#

Regex is simple, easy to implement, and performs validation for a given email address relatively quickly. They allow developers to implement robust validation without complication.

The Limitations of Regex in C#

One of the potential drawbacks of Regex in C# is that they can be quite difficult to maintain. A Regular expression in your code should always be explained by descriptive comments. It is important to note that without well commented Regex code, complications will arise down the line. 

A limitation of using Regex to validate an email address is the fact that Regex only checks the formatting of the email. Regex does not check that the mail address is actually real, legitimate, and in use. 

For example, you could have the following email address, abc@123.com. This email address would pass any Regex email validation checks, but there is no way for Regex to check that this is actually a valid email address. 

To do this you would have to check the SMTP server and MX records of that address. 

  • An SMTP server is a Simple Mail Transfer Protocol server, it is how emails are sent and received by applications. This is what is meant by an SMTP protocol.
  • MX records are Mail Exchange (MX) records. These are DNS records that are necessary for sending emails to an email address. 

Check out our alternatives to Regex below to learn more about this. 

Alternatives to validating email addresses in C#

You are not limited to performing your email validation in C#. You can use a different programming language to validate emails, such as Ruby. You could also use JavaScript to validate your emails. Client-side validation could prove to perform much faster in many cases and may make more sense for your use case.

Another possibility would be to use an API for email validation. Many companies opt to use an API for email validation as it allows for them to validate many emails at once, generate JSON files containing the emails that have failed the checks, and APIs can validate the MX fields and SMTP server of a target domain. 

You can read more about MX fields and SMTP server checks here, but it is essentially checking the validity of the email domain itself by checking MX records and SMTP server use. This is an additional layer of validation that the use of APIs can provide. Check out the Abstract Email Verificiation and Validation API to learn more. You can get started for free, and use it for your own web application or personal project at no cost.

Emma Jagger

Emma Jagger is an experienced engineer and Google alumna with a degree from Carnegie Mellon University. She specializes in email validation, IP geolocation, and API integration, focusing on creating practical and scalable solutions through her technical writing.

Get your free
Email Validation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
Email Validation
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required