Question

I am trying to use validates_format_of in my model file to validate an email address. However, I need to enter two regexes for two special cases. Basically, only a few top-level domain names are allowed.

However, it seems according to the source code for validates it only allows one :format key and one set of options as the hash value. Is there a way to use multiple regexes. I have tried the logical operators but it seems to accept only the first one. Also, using two validates method on the same field leads to nothing getting accepted as one violates the other condition

To explain in actual terms, say I want to only emails that are either gmail or yahoo and nothing else. How do I use regexes to represent both and nothing else? This is my gmail code and it works:

validates_format_of :email, :with => (/^([^@\s]+)@((?:gmail+.)+[a-z]{2,})$/i)

How do I change it to include another top level domain name?

Was it helpful?

Solution

validates_format_of :email, 
    :with => (/^([^@\s]+)@((gmail|yahoo|hotmail)\.+[a-z]{2,})$/i)

something like this?

[a-z] at the end won't capture something like '.com.au' or similar, is that okay?

Also,

. is for single character, you want \. for an actual period
otherwise 'gmailxcom' would be valid

OTHER TIPS

To build upon the answer of @Neet324, you could use:

validates_format_of :email, :with => (/^([^@\s]+)@((\.?\w+)+)$/i)

to capture any email domains, including subdomains and country level top domains.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top