Ask A Question

Notifications

You’re not receiving notifications from this thread.

validate presence of specific domain in email

JM 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\-]+@mydomain\.org\z/, message: "must be a mydomain.com account" }
Reply

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.

Reply

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

will try with @ and the domain separated

Reply

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.

Reply

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

Reply

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

Reply
Join the discussion
Create an account Log in

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

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

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