Email validation regex

Updated . Posted . Visible to the public.

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.

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.

Jakob Scholz
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Jakob Scholz to makandra dev (2019-10-31 15:01)