How to add a User model validation to block certain email domains

我们两清 提交于 2020-01-05 04:15:10

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/9708280/how-to-add-a-user-model-validation-to-block-certain-email-domains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!