Read more

Email validation regex

Jakob Scholz
October 31, 2019Software engineer at makandra GmbH

There is a practical short list for valid/invalid example email addresses Show archive.org snapshot - Thanks to Florian L.! The definition for valid emails (RFC 5322) can be unhandy for some reasons Show archive.org snapshot , though.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Since Ruby 2.3, Ruby's URI lib provides a built-in email regex URI::MailTo::EMAIL_REGEXP. That's the best solution to work with.

/\A[a-zA-Z0-9.!\#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\z/

Note that this allows addresses like user@example which are technically correct, but almost never valid as a user email address in web applications. To force a domain with TLD, simply adjust:

/\A[a-zA-Z0-9.!\#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+\z/

A less restricting pattern

If you want to be less restrictive about the email verification, you can use the default regex from Devise:

Devise.email_regexp

=> /\A[^@\s]+@[^@\s]+\z/

Other patterns we used in the past

See also our card regarding DNS validation of e-mail adresses.

Posted by Jakob Scholz to makandra dev (2019-10-31 16:01)