Sunday, July 26, 2009

Update your Email Regex - JavaScript

Regular Expressions are a common tool in aiding developers to write compact matching functions which are frequently used for error checking on forms. In particular, one of the most common fields to appear on a form is an email field. And with the emergence of newer email syntax behaviors like appending the ‘+’ (plus sign) symbol which allows Gmails users to filter incoming mail to be sorted by folder, tagged with a star, and/or directly archived, there is a need for an updated common regular expression.

Let’s look at the most common email regular exression:

Common Email Regular expressions

var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

This pattern matches anything that has ‘one of more of’ a through z (lowercase and/or uppercase), 0 through 9, an underscore (_), a dot (.), or a hyphen(-)…. Then followed by a required @ symbol. Then followed by (a through z (upper and/or lower), and/or 0 through 9, and/or a hyphen) followed by a required dot (.). Then lastly followed by an alpha-numeric string that is 2 to 4 characters long. This now allows Gmail users to add their filtered addresses such as user+filter@gmail.com. I hope this short tip was helpful. Enjoy!

Ok, take a deep breath. What’s missing?. That ‘addition’ symbol. So without looking too much farther, and without having to explain it all over again, here is our revised regular expression.

Revised and New Regular Expression

var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

This now allows Gmail users to add their filtered addresses such as user+filter@gmail.com. I hope this short tip was helpful. Enjoy!

0 comments:

Post a Comment