David Celis

Little posts on the prairie, from a cowboy coder

Stop Validating Email Addresses With Regex

Just stop, y’all. It’s a waste of your time and your effort. Put down your Google search for an email regular expression, take a step back, and breathe. There’s a famous quote that goes:

Some people, when confronted with a problem, think, “I know, I’ll use regular expressions.” Now they have two problems.

Jamie Zawinski

Here’s a fairly common code sample from Rails Applications with some sort of authentication system:

class User < ActiveRecord::Base
  # This regex is from Devise, the most popular Rails authentication library
  validates :email, format: {with: /\A[^@][email protected]([^@\.]+\.)+[^@\.]+\z/}

If you’re experienced at Regex, this seems simple. If (like me when I first saw this) you AREN’T experienced at Regex, it takes a while to parse. But believe me, it can get way worse…

    class User < ActiveRecord::Base
      validates :email, format: {with: /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9][email protected]((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i}

Or even worse still…

    class User < ActiveRecord::Base
      validates_with EmailAddressValidator

    class EmailAddressValidator < ActiveModel::Validator
      EMAIL_ADDRESS_QTEXT           = Regexp.new "[^\\x0d\\x22\\x5c\\x80-\\xff]", nil, "n"
      EMAIL_ADDRESS_DTEXT           = Regexp.new "[^\\x0d\\x5b-\\x5d\\x80-\\xff]", nil, "n"
      EMAIL_ADDRESS_ATOM            = Regexp.new "[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+", nil, "n"
      EMAIL_ADDRESS_QUOTED_PAIR     = Regexp.new "\\x5c[\\x00-\\x7f]", nil, "n"
      EMAIL_ADDRESS_PATTERN         = Regexp.new "#{EMAIL_ADDRESS_SPEC}", nil, "n"
      EMAIL_ADDRESS_EXACT_PATTERN   = Regexp.new "\\A#{EMAIL_ADDRESS_SPEC}\\z", nil, "n"

      def validate(record)
        unless record.email =~ EMAIL_ADDRESS_EXACT_PATTERN
          record.errors[:email] << "is invalid"

Yikes! Is something that complex really necessary? If you actually check the Google query I linked above, people have been writing (or trying to write) RFC-compliant regular expressions to parse email addresses for years. They can get ridiculously convoluted as in the case above and, according to the specification, are often too strict anyway. To add to the annoyance, many regular expressions for email addresses that you can find on the web will show the now-commonplace practice of tagging emails (e.g. [email protected]) as invalid.

Sections 3.2.4 and 3.4.1 of the RFC go into the requirements on how an email address needs to be formatted and, well, there’s not much you can’t do in your email address when quotes or backslashes are involved. The local string (the part of the email address that comes before the @) can contain any of these characters: ! $ & * - = ^ ` | ~ # % ' + / ? _ { }

But guess what? You can use pretty much any character you want if you escape it by surrounding it in quotes. For example, "Look at all these spaces!"@example.com is a valid email address. Nice.

For this reason, for a time I began running any email address against the following regular expression instead:

    class User < ActiveRecord::Base
      validates :email, format: {with: /@/}

Simple, right? Email addresses have to have an @ symbol. This is often the most I do and, when paired with a confirmation field for the email address on your registration form or something like Kicksend’s mail checker, can alleviate most problems with user error. But what if I told you there were a way to determine whether or not an email is valid without resorting to regular expressions at all? It’s surprisingly easy, and you’re probably already doing it anyway.

Just send them an email already

No, I’m not joking. Just send your users an email. The activation email is a practice that’s been in use for years, but it’s often paired with complex validations that the email is formatted correctly. If you’re going to send an activation email to users, why bother using a gigantic regular expression?

Think about it like this. I want to register for your website, which requires my email address, but I don’t want to give it to you, so I just type in [email protected]. That’s going to bounce, but the formatting is fine; it’s a valid email address. To get around this problem, you implement an activation system where, after registering, I’m sent an email with a link I have to click in order to activate my account so I can prove that I actually own that email address I entered. At this point, why keep parsing email addresses for their format? The result of sending an email to a badly formatted email address would be the same: it’ll get bounced. If your user enters a bad email address, they won’t get the activation email and they’ll try to register again if they really care about using your site. It’s that simple.

So eschew your fancy regular expressions already. If you really want to check email addresses while your users are signing up, use the aforementioned mail checker or a similar tool. If your user enters a bad email address, you shouldn’t make it more of a problem for yourself than you have to. A complex regex validation on the email address doesn’t introduce an additional solution, it introduces an additional problem.

David Celis @davidcelis

✍️ Reply via email