markneustadt.com

The easiest and best way to validate an email address

When someone enters an email address, how do we check to make sure it’s legit?  Not legit as in “is it really their email address”, but as in “does it follow the rules to make it a real email address”?

For example, if someone enters “jdshfjsdhf”, that’s not legit.  However, “jskfjsd@jskdjcfs.com” is.  Recently, I ran into a problem where my scheme for validating email addresses was failing me.

Preveiously, I had been using a regular expression.  My routine looked like this…

BadCode

For reference, that copy and pastable regular expression is:

string MatchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

That sucks.  More specifically, it was failing on a gmail address with a plus sign in it.  Those are totally legit (and super handy), but my regular expression didn’t agree.  “somerandomuser+001@gmail.com” was failing.

A MUCH better way is to offload that to the framework.  Now, my code looks like this:

GoodCode

See?  Much easier.  And again, for copy and paste simplicity, here you are:

public static bool IsEmail(string prospectiveEmailAddress)
{            
    try
    {
        System.Net.Mail.MailAddress m = new    
                System.Net.Mail.MailAddress(prospectiveEmailAddress);  
        return true;
    }
    catch
    {
        return false;
    }
}

Scroll To Top