Four Regular Expressions to Check Email Addresses
How do you find out if a user has entered a valid email address? Do you check for an at-sign, or is it more complicated? For many developers the answer is a regular expression, a little bit of code that can describe text patterns using wildcards and other special characters. If you’re new to the topic, we have a great regular expression tutorial.
Here are four regular expressions (often called regexes) that all validate the format of an email address. They have increasing degrees of complexity. The more complicated, the more accurate each is at matching only email addresses.
1. Dirt-simple approach
Here’s a regex that only requires a very basic email@example.com:
Upside: Dirt simple.
Downside: Even invalid email addresses like firstname.lastname@example.org, or even email@example.com, make it through.
2. Slightly more strict (but still simple) approach
Regular-Expressions.Info provides a basic email validation regex that tries to be a little smarter:
Upside: Only allows email address-friendly characters, restricts domain extension to only two to four characters.
Downside: It still allows many invalid email addresses, and misses some longer domain extensions (.museum, for example).
3. Specify all the domain extensions approach
Upside: It doesn’t allow firstname.lastname@example.org!
Downside: Upkeep could be tough with this one. You’d have to update any time new domain extensions are announced. In fact, you already would need to add the .me extension.
4. Way complicated approach
A Perl module has a long regular expression based on the standard description of an email address. It’s so long (nearly 6,500 characters!) that I won’t include it here.
Upside: It’s complete.
Downside: It’s way complicated.
Meet in the middle approach
You’ll have to decide, if you haven’t already, which regular expression to use. Likely, you’ll choose somewhere in the middle of the examples we’ve given. Regular-Expressions.Info has a good run-down of the trade-offs of different approaches.
Have you already decided how to check email addresses? How do you do it?