Validates_each to allow only specific emails?

for my rails3, devise, users model (name, email address, etc.). I want the forbidden domain names to be registered on the site.

The idea is that I have a list of blacklisted domains (badplace.com, hotmail.com) ... and when the new user record is saved, I will check the letter if it has a domain with a bad domain, I add a mistake.

So what is the right way to implement this in Rails ...

Here is what I played with:

In user model

protected
  validates_each :email, :on => :create do |record, attr, value|
     domain = email.split("@").last
     record.errors.add attr, "That a BAD EMAIL." unless value && !value.contains(domain)
  end

What do you think?

+3
source share
1 answer

You can do this more easily with validates_format_ofregular expression:

class User < ActiveRecord::Base
  validates_format_of :email, :without => /badplace\.com|hotmail\.com/, :message => "That a BAD EMAIL."
end

EDIT:

- :

INVALID_EMAILS = %w(badplace.com hotmail.com)
validates_format_of :email, :without => /#{INVALID_EMAILS.map{|a| Regexp.quote(a)}.join('|')}/, :message => "That a BAD EMAIL."
+4

Source: https://habr.com/ru/post/1786797/


All Articles