All threads / validate presence of specific domain in email

Ask A Question

Notifications

You’re not receiving notifications from this thread.

validate presence of specific domain in email

John Munyi asked in General

Hi there, is a way via regex to validate an email and make sure it belongs to a specific domain, I found the below regex on SO and it doesnt seem to do the job.

validates :email, format: { with: /\b[A-Z0-9._%a-z\-][email protected]\.org\z/, message: "must be a mydomain.com account" }

Your code is looking for mydomain.org but your error message says mydomain.com. Is that causing the problem?

Other than that, if you don't want to use regex you could split the email string on the @ symbol and verify the last string in that array matches mydomain.com.

I used "mydomain" just as an example ... i had replaced all that with the specific domain.

will try with @ and the domain separated

I get that but I just wanted to point out in your Regex you're looking for .org and your error message says your looking for .com. So, if you're passing in .com email addresses it won't save that object because it doesn't pass your :email validation, which could be why it's not working.

The posted regex should work so long as you are passing in the whitelisted FQDN into the regex pattern.

When in doubt, practice your regex patterns on Rubular

Finally worked , the issue was separating "@" and the "domain.org" part i used
[email protected]+mydomain.org

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,344+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.