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:
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:
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:
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 “firstname.lastname@example.org”, 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#.
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:
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:
Now add the code in the following example, which determines whether the specified value matches the pattern of a valid email address:
Let’s see how use this method to check if an email address is valid:
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, email@example.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#
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.