Skip to content

Instantly share code, notes, and snippets.

@awesome
Forked from jpmckinney/email_validator.rb
Created July 7, 2016 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awesome/3aaae12f4c9ce611ba4d0cd99078b628 to your computer and use it in GitHub Desktop.
Save awesome/3aaae12f4c9ce611ba4d0cd99078b628 to your computer and use it in GitHub Desktop.
Email validation in Rails 3 or Active Model without regexp
# blog post: http://blog.slashpoundbang.com/post/12694519460/email-validation-in-rails-3-or-active-model-without
# http://my.rails-royce.org/2010/07/21/email-validation-in-ruby-on-rails-without-regexp/
class EmailValidator < ActiveModel::EachValidator
# Domain must be present and have two or more parts.
def validate_each(record, attribute, value)
address = Mail::Address.new value
record.errors[attribute] << (options[:message] || 'is invalid') unless (address.address == value && address.domain && address.__send__(:tree).domain.dot_atom_text.elements.size > 1 rescue false)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment