1

I would like to have a list of email domains that are validated against to prevent from registering on my app.

10minutemail.com, yopmail.com, mail.com, mail.ru etc...

I have a list of domains in my user model like so:

BAD_DOMAINS = [/10minutemail.com/, /yopmail.com/, /mail/

I would like to add a User validates on the email field to add an error if the user is registering with one of these domains.

BAD_DOMAINS.each { |rule| return true if !domain.match(rule).nil? }

I have that regex working, but how do I add that as a validates? I tried this:

validates :email, :format => { : exclusion => BAD_DOMAINS,
        :message => "%{value} no good." }

Thanks

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

1 Answers1

2

You need to combine all of your separate regular expressions into a singular one, but you might find it's easier to do that if you have a list of strings instead of a list of regular expressions:

EXCLUSION_DOMAINS = %w[
  example.com
  test.com
  asdf.com
]

EXCLUSION_REGEXP = Regexp.new('(?:' + EXCLUSION_DOMAINS.collect { |d| Regexp.escape(d) }.join('|') + ')$')

You'll want to ensure that things don't match this, so it's a little different to use:

validates :email,
  :format => {
    :with => VALID_EMAIL_REGEXP,
    :without => EXCLUSION_REGEXP,
    :message => "%{value} no good."
  }

You should use some kind of valid email tester as well to be sure the address is plausible. It's expressed here as VALID_EMAIL_REGEXP which is some kind of email validator regular expression. Try and use an RFC compliant one if you do that.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 1
    Thanks ... There isn't a way to validate the email is valid with? validates :email, :presence => true, :email => true – AnApprentice Mar 14 '12 at 19:51
  • It seems you have to split this validator in tow parts as long as you cannot use both :with and :without. – pimpin Dec 07 '18 at 17:29