Ruby already has its own regular expression to validate emails

I’ve searched and written a lot of regular expressions to validate email on our models and forms but recently I’ve found out that Ruby already has a good one and its easy to access and use.

All you have to do require uri library and use its constant:

require 'uri'
'user@gmail.com'.match(URI::MailTo::EMAIL_REGEXP).present?

It’s also easy to use on an Active Record format validation:

validates :email, format: { with: URI::MailTo::EMAIL_REGEXP, message: "only allows valid emails" }

It even accepts emails with “+” as gmail enables.

 

Leave a Comment