Say Goodbye to Complex Regex: Simplifying Email Validation in Ruby on Rails

Gonzalo Galdámez
Unagi
Published in
2 min readApr 12, 2024
Say Goodbye to Complex Regex

Avoid dealing with long and complex regular expressions to validate email addresses in your Ruby on Rails models. You can make your code cleaner and more straightforward by using URI::MailTo::EMAIL_REGEXP.

The Custom RegEx Way

validates :email, format: { with: /\A[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\z/ }

While it’s possible to craft a powerful regex using today’s tools (AI makes it easy peasy), navigating through the sea of symbols and character classes can be an exhausting task. So let’s see a better way, the Rails Way!

The Rails Way

validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }

Ah, much better! By using URI::MailTo::EMAIL_REGEXP, you're tapping into a built-in regular expression provided by Ruby that's specifically designed for email validation. It's concise, clear, and does the job perfectly.

By using this built-in expression, you get the best of Rails worlds:

  1. Readability: Your code becomes easier to read and understand for you and your fellow developers.
  2. Maintenance: You don’t have to worry about updating your regex when email validation standards change. URI::MailTo::EMAIL_REGEXP stays up-to-date for you.
  3. Efficiency: Less time spent deciphering regex means more time building awesome features for your Rails app.

So, the next time you need to validate an email address in your Rails model, keep it simple and effective with URI::MailTo:

Unagi provides software development services in #Ruby and #JavaScript, a stack we still choose after +11 years. Check out more about us.

--

--