Several Easy Ways to Validate Email Addresses in C#Instead of using a regex to validate email addresses, there are built in tools which can perform the task just as well, if not better.
Instead of using a regular expression to validate an email address, you can use the built-in functions of the MailAddress class or Data Annotations.
It used to be that regular expressions were the best method to validate email addresses in C#, but with all the new Top Level Domains (TLD's) flying around and new ones being released, this is becoming an increasingly difficult task. So instead, why not let Microsoft do the hard work of validating email addresses in C#?
Validate Email Addresses with Data Annotations
Data Annotation Model Binder performs validation within an ASP.NET MVC application, although you can reference the assembly and namespace in any project type.
Add a reference to the Microsoft.Web.Mvc.DataAnnotations.dll assembly and the System.ComponentModel.DataAnnotations.dll assembly from within the Project options > Add Reference dialogue.
Next, add the namespace and the code to validate an email address.
using System.ComponentModel.DataAnnotations
public static bool IsEmailValid(string emailaddress)
{
return new EmailAddressAttribute().IsValid(emailaddress);
}
Validate Email Addresses using Regular Expressions
Regular Expressions, or Regex, are another popular method for validating mail addresses in your C# code.
public static bool IsEmailValid(string emailaddress)
{
/ returns true if the input is a valid email
return Regex.IsMatch(emailaddress, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
Validate Email Addresses with MailAddress
The .Net library gets updated regularly with all the new validation methods automatically across all platforms (forms, asp.net etc..) meaning you need only call their methods from your code and you are up to date.
Instead of using a regular expression to validate an email address, you can use the System.Net.Mail.MailAddress class. To determine whether an email address is valid, pass the email address to the MailAddress.MailAddress(String) class constructor.
Source: Microsoft ASP.Net Website
public bool IsEmailValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}