2

I have read about similar case here: Validation specific email specific domain devise 3 ruby on rails 4

However, it's only one email domain (e.x. example.com). What I want is to alloww some email domains that I have (ex. domain1.com, domain2.com, domain3.com, etc.). How to achieve that?

Community
  • 1
  • 1
Arief R Ramadhan
  • 234
  • 3
  • 16

3 Answers3

7

you can add the following code in your model

  validate :email_domain

  def email_domain
    domain = email.split("@").last
    if !email.blank?
      errors.add(:email, "Invalid Domain") if domain != "gmail.com"
    end
  end

You can add as many domain you want to allow.

  • Thank you for the answer. But it takes too many lines if you put it in the model like that. Is it possible to set a variable and then get the email domain lists in another file or maybe in the bottom of the model file? If yes, then how the code will looks like? – Arief R Ramadhan Feb 20 '16 at 15:14
  • You can define a array of domains that you want to allow and check that array includes the domain of the given email or not – PITABAS PRATHAL Feb 20 '16 at 18:04
3

I use the code by Pavan in other thread (Allow only specific emails to register in Rails app (Devise)) and it's working.

To allow specific email, I use these code to my user model:

validates :email, format: { with: /\b[A-Z0-9._%a-z\-]+@xyz\.com\z/, message: "must be a xyz.com account" }
Community
  • 1
  • 1
Arief R Ramadhan
  • 234
  • 3
  • 16
2
APPROVED_DOMAINS = ["domain_one.com", "domain2.com"]
* or you can load this from somewhere else

validates :email, presence: true, if: :domain_check

def domain_check
  unless APPROVED_DOMAINS.any? { |word| email.end_with?(word)}
    errors.add(:email, "is not from a valid domain")
  end
end
maxcobmara
  • 391
  • 2
  • 9
  • 1
    I would add an additional validation like https://stackoverflow.com/a/35519515/595152 did, because this means validate presence of email only when domain is correct – Betty St May 17 '18 at 12:19
  • I love this solution. Because I could add as many domains as I like. Beside validation is fantastic to have, I don't know if validation for many domains could be done.!!! – egyamado May 24 '21 at 07:41