John Otander

Email Format Validator for Rails

I made a gem called Email Format that utilizes the validate_each method that’s included in ActiveModel::Validations. It uses the email_regex gem written by Doug Wiegley which “provides a valid email regex that conforms to most valid RFC edges cases (disallows backticks), and allows for a few illegal patterns that are in common use”.

The validator itself is very simple, it simply compares the attribute in question to the EmailRegex::EMAIL_ADDRESS_REGEX like so:

class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ EmailRegex::EMAIL_ADDRESS_REGEX
      record.errors[attribute] << (options[:message] || "is invalid")
    end
  end
end

So, you can now do the following to validate your email attributes:

require 'email_format'

class Awesome
  include ActiveModel::Validations

  attr_accessor :email

  validates :email, email_format: true
 end

 awesome = Awesome.new

 awesome.email = "valid@email.com"
 awesome.valid? # => true

 awesome.email = "invalid_email"
 awesome.valid? # => false

See the Github repo


Sign up for my newsletter

If you want early access to what I'm researching, writing, and building, you should subscribe to my newsletter.

No spam, ever. You can unsubscribe at any time.