Created
May 13, 2014 15:12
-
-
Save lmmendes/3512041f9a6fbfd66caf to your computer and use it in GitHub Desktop.
Simple email validator for ActiveModel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
class EmailValidator < ActiveModel::EachValidator | |
# Validates that the specified attribute is a valid e-mail address | |
# | |
# class Person < ActiveRecord::Base | |
# validates :email, :email => true | |
# end | |
# | |
# The validator expects that the e-mail not blank | |
# | |
# Configuration options: | |
# * <tt>:message</tt> - A custom error message | |
# | |
# There is also a list of default options supported by every validator: | |
# +:if+, +:unless+, +:on+ and +:strict+. | |
# See <tt>ActiveModel::Validation#validates</tt> for more information | |
def validate_each(record, attribute, value) | |
# try to match and grab the entire value between @ and the end of the string | |
# so "luis@gmail.com" should return "gmail.com" | |
is_match = value.to_s.match(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i) | |
# if "is_match" is nil it's because the provided value is not a valid e-mail | |
if is_match.nil? | |
record.errors[attribute] << (options[:message] || :invalid) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment