1

I want to validate email address with a particular suffix which should be like email. It must have .edu or must have @mypost.com. As an example, I have four email addresses as shown below:

1) john@learn.edu - valid

2) john@mypost.com - valid

3) john@gmail.com - invalid

4) john@dblist.org - invalid

I have tried to solve the problem using the below code in my user.rb model file but to no avail.

if ('xc@dblist.com' =~ /\A[\w]([^@\s,;]+)@((mypost|[\w-]+\.)+(edu|com))\z/i) != nil
  return true
else
  return false
end
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
rick
  • 1,675
  • 3
  • 15
  • 28
  • 1
    Add all the rules for valid email format – Tushar Jul 23 '15 at 12:58
  • the conditional is not needed `=~` will either return `nil` or a `Fixnum`. `nil` is a falsey value and `Fixnum` will be a truthy value so the if statement becomes redundant. [Docs](http://ruby-doc.org/core-2.2.0/String.html#method-i-3D-7E) – engineersmnky Jul 23 '15 at 13:22

3 Answers3

1

You can use this regex:

\A\w([^@\s,;]+)@(mypost\.com|[\w-]+\.edu)\z

See demo (I use ^/$ for demo in multilingual mode there)

The (mypost\.com|[\w-]+\.edu) part matches any .EDU domain and MYPOST.COM.

Note that if you do not use captured groups, just use \A\w[^@\s,;]+@(?:mypost\.com|[\w-]+\.edu)\z.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Sorry stribizhev, but i don't know how i can use this in my `if` condition and i have edit my question. Thank you for answer. – rick Jul 23 '15 at 13:23
  • Please check this [SO post](http://stackoverflow.com/a/4849241/3832970), perhaps it has some hints on what is wrong. In Ruby, [your code and my regex work OK](http://ideone.com/rCENu6). – Wiktor Stribiżew Jul 23 '15 at 13:30
1
\A\w([^@\s,;]+)@(?:([\w-]+\.)+edu|mypost\.com)\z

Try this.See demo.

https://regex101.com/r/oC5rY5/2

vks
  • 67,027
  • 10
  • 91
  • 124
1

Here is a fairly simple one that seems to meet your rules:

^[\w\-\.]+@(?:(?:[\w\.\-]+\.edu|mypost\.com))$

Example

this part [^@\s;,] is not needed since \w will not capture these anyway.

Note: regex101.com is a great resource for understanding your regex. Example of your regex Explanation is on the right. I think with will help you understand why yours is not working.

engineersmnky
  • 25,495
  • 2
  • 36
  • 52