Skip to content

Instantly share code, notes, and snippets.

@jpmckinney
Created November 12, 2011 17:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jpmckinney/1360858 to your computer and use it in GitHub Desktop.
Save jpmckinney/1360858 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