Monday, November 22, 2010

Best Validation Expression for Email Address

If you've been playing around with the ASP.NET Regular Expression Validator or any other RegEx tools, then you've more than likely had to check an email addresses for its validity at some point.

Email Address values can range all over the place, which makes them somewhat difficult to correctly validate, especially because you don't want someone to not be able to complete a form if their email address doesn't comply with the regular expression you've chosen, or worse, you don't want someone to input an incorrect email address to abide by your validation expression.

I've been testing various expressions that I've been hunting down across the internet and I've found what I believe the be the best on the simple url: http://www.regular-expressions.info/email.html

This site addresses the RFC 2822 standard and makes some minor tweaks to it, leaving you with two options. The better of which is [a-z0-9!#$%&'*+/=?^_`{}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}comorgnetedugovmilbizinfomobinameaeroasiajobsmuseum)\b

However, the above expression does require constant review, as it specifically spells out the top level domains. As new domains are created, they will need to be added to this list. So, tomorrow if the new top level domain was created .webdev (i.e. rob@digitalplaydoh.webdev) then, you would need to add webdev to this expression to allow for all email addresses to be valid.

Rather than constantly need to check on these top-level domains, I much prefer a tweaked version that allows for a much less strict set of top-level domains, including those that don't exist such as rob@digitalplaydoh.fake. It gives the user the ability to provide a fake email address, but at least I know it's an email address in a proper format.

Therefore, I find this to be the most accurate email address regular expression:
[a-z0-9!#$%&'*+/=?^_`{}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

0 comments:

Post a Comment