Created
January 10, 2015 13:15
-
-
Save alecslupu/22111497316d5a860cf8 to your computer and use it in GitHub Desktop.
EmailExclusionValidator
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
class EmailExclusionValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
unless value =~ email_regex | |
record.errors[attribute] << (options[:message] || "is not an email") | |
else | |
user_name = value.split('@').first | |
if forbidden_words.include?(user_name) | |
record.errors[attribute] << (options[:message] || "you cannot register with a user name") | |
end | |
end | |
end | |
private | |
def forbidden_words | |
%w(admin) | |
end | |
def email_name_regex | |
'[\w\.%\+\-]+' | |
end | |
def domain_head_regex | |
'(?:[A-Z0-9\-]+\.)+' | |
end | |
def domain_tld_regex | |
'(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum)' | |
end | |
def email_regex | |
/\A#{email_name_regex}@#{domain_head_regex}#{domain_tld_regex}\z/i | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment