Skip to content

Instantly share code, notes, and snippets.

@alecslupu
Created January 10, 2015 13:15
Show Gist options
  • Save alecslupu/22111497316d5a860cf8 to your computer and use it in GitHub Desktop.
Save alecslupu/22111497316d5a860cf8 to your computer and use it in GitHub Desktop.
EmailExclusionValidator
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