How to Validate Email Addresses in C#

I was recently doing doing support for a client that had a newsletter system. The previous employee had neglected to do much in the form of format validation for email addresses from both a user-input standpoint and system-integrity standpoint. Since there were several email addresses in the database that didn’t meet the basic conventions of an email address, the user received the following error whenever she tried to send out a message:

Exception Details: System.FormatException: The specified string is not in the form required for an e-mail address.

Ouch. To remedy this issue, I added a check to make sure the email address was valid before it attempted to send the message. In the code below, I’m making use of the System.Text.RegularExpressions library that comes with the .NET framework. The code below is written in C# but the code will be very similar in Visual Basic. It will also work in ASP.NET, WPF or plain old windows forms.

Here’s a C# function that will determine whether or not an email address is valid:

public static bool IsValidEmail(string strEmailAddress)
{
if (strEmailAddress == null)
{
return false;
}
else
{
return System.Text.RegularExpressions.Regex.IsMatch(strEmailAddress, @"^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\.(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|[a-zA-Z]{2})$", RegexOptions.IgnorePatternWhitespace);
}
}

I also made some modifications to the system on the front-end, so when a user registered from then on, that it would validate that they have entered an email address and that the email address matched the format of an email address using a RequiredFieldValidator and a RegularExpressionValidator.<–>

Comments

  1. This don’t take account for the underscore _ so it will set a email like myeamil_@hotmail.com as false.
    This is a valid email in real life thow

Speak Your Mind

*