Rails - validates_each to allow only certain Emails?
for my rails3, devise, users model (name, email, etc...) I want to prevent bad domains from registering on the site.
The idea being I have a list of blacklisted domains (badplace.com, hotmail.com) ... and when a new user record goes to be saved, I check the email, if it has a domain with 开发者_StackOverflowa bad domain, I add an error.
So what's the right way to implement this smartly in Rails...
Here's what I've been playing with:
In the User's Model
protected
validates_each :email, :on => :create do |record, attr, value|
domain = email.split("@").last
record.errors.add attr, "That's a BAD EMAIL." unless value && !value.contains(domain)
end
What do you think?
You can do this more easily with a validates_format_of
and a regular expression:
class User < ActiveRecord::Base
validates_format_of :email, :without => /badplace\.com|hotmail\.com/, :message => "That's a BAD EMAIL."
end
EDIT:
For many addresses, you can do something like this:
INVALID_EMAILS = %w(badplace.com hotmail.com)
validates_format_of :email, :without => /#{INVALID_EMAILS.map{|a| Regexp.quote(a)}.join('|')}/, :message => "That's a BAD EMAIL."
精彩评论