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. In this article, we are going to explore a few different ways to validate email addresses. First, we’ll use built-in classes and then, regex and other approaches.
We have a lot to cover, so let’s start.
Understand Email Address Composition
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: !#$%&’*+-/=?^_`{|}~.
It is good to mention that the second section must have at least one period, and we cannot use two periods adjacent nor as the first or the last character in any of these sections.
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 our first method:
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.
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:
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 versions before 4.x, it uses a regular expression to validate the email address. However, in more recent versions, it simply checks if the string contains a @
symbol and if this symbol is not at the beginning or the end of the string.
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
If we are using .NET 7 (a version later than 4.x) the EmailAddressAttribute
simply checks for the presence of a ‘@’ symbol and if it is not at the beginning or end of the string. Therefore, the email address [email protected]
is valid according to this validation method.
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:
public bool ValidateUsingRegex(string emailAddress) { var pattern = @"^[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.
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
Then, let’s set up our validation:
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 behaves exactly like the most recent versions of the EmailAddressAttribute
class.
Alternatively, we can pass the EmailValidationMode.Net4xRegex
enum to validate it using regex:
public class EmailFluentValidator : AbstractValidator<string> { public EmailFluentValidator() { RuleFor(email => email) .EmailAddress(EmailValidationMode.Net4xRegex); } }
Now, the same method considers the email address ([email protected]
) invalid.
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.
It is important to note that we don’t have a single perfect approach, and choosing the right methods depends on specific requirements such as the level of strictness, complexity, customization, and performance. Once we are looking for performance or low complexity, the MailAddress class or the EmailAddressAttribute are good options. However, in case we need to customize our solution, FluentValidation allows us to choose which way we want to validate our email addresses.
In the last case, if we need a high level of strictness and better validation, using regular expression is the best approach because we can define specific rules for validating the format of an email address. On the other hand, it is more complex and harder to maintain than other approaches.
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.