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
- https://makandracards.com/makandra/77-handy-a-regex-that-validates-all-valid-email-addresses-give-or-take-axon-flux-a-ruby-on-rails-blog
- https://makandracards.com/makandra/12127-regex-pattern-to-validate-email-addresses
See also our card regarding DNS validation of e-mail adresses.
Posted by Jakob Scholz to makandra dev (2019-10-31 15:01)