July 22, 2009

A Solution To E-Mail Validation

Whenever it comes time to validate an email address, I always end up going through the same exact process.

I start with a simple regular expression— for example, this:


It works great for a majority of email addresses— however, it is not perfect. It lets through a lot of invalid email addresses. For example, ".name@something.a" is considered a valid email address by this regular expression. So, let's take a few steps to correct this:


A bit better, right? But what about valid email addresses, such as john+smith@mail.something.com and $A12345@example.mobile? Same goes for the seemingly invalid email addresses such as "Abc\@def"@example.com. But, alas, these are all valid.

No, I am not going to even attempt a regex that accommodates these. Others have tried. However, it is futile; email validation ends up either being too strict with what it rejects, or too liberal with what it lets through. Or, in many cases— both.

But for the sake of argument, let's assume we do create a regex that follows the RFC perfectly. That still doesn't stop people from getting through with something like youre.bad@validation.com. Sure, we could even go as far as checking to make sure it is a real, actual email address. But even then, there is no stopping johnsmith@gmail.com— an email address that surely exists, however probably is not owned by the person filling out the form.

Depressing, huh?

Well, what about this one:


Here's the secret. This is not a programming problem- it's a usability issue. If the user benefits from giving you their real email address, they will. If not, you should not be asking for an email address.

It is that simple, really. Just make sure they at least attempted an email address (otherwise, they may mix up the fields), and throw in a good reason to hand it over- and you will never have a problem.

Thanks to Chancey Matthews for reminding me checking for an @ symbol is good enough, and haacked.com for reading the RTC so I didn't have to.

About Gregory Koberger

I'm a freelance developer and designer, formerly of Mozilla. I talk a lot about web development, technology and user experience — sometimes on my blog but mostly on Twitter.

Keep Reading

Your Turn