Add to your Gemfile:
gem 'email_validator'Run:
bundle install
Then add the following to your model:
validates :my_email_attribute, email: trueIf you'd like to validate an email outside of a model then here are some class methods that you can use:
EmailValidator.regexp # returns the regex
EmailValidator.valid?('narf@example.com') # => true
EmailValidator.invalid?('narf@example.com') # => falseThe validation provided by this gem is loose. It just checks that there's an @ with something before and after it. See this article by David Gilbertson for an explanation of why.
Your users may accidentally submit leading or trailing whitespace when submitting a form. You may want to automatically trim this. This is not the job of a validator gem but it's trivial to implement yourself by adding a setter in your model:
def email=(e)
e = e.strip if e
super
endYou may also want to convert emails to lowercase in the same way.
Do you prefer a different email validation gem? If so, open an issue with a brief explanation of how it differs from this gem. I'll add a link to it in this README.
This gem is thread safe.
