I have this regex for email validation (assume only [email protected], [email protected], [email protected] are valid)
/^[a-zA-Z0-9]+@[a-zA-Z0-9]\.(com)|(edu)|(org)$/i
But @abc.edu and [email protected] are both valid as to the regex above. Can anyone explain why that is?
My approach:
there should be at least one character or number before @
then there comes @
Try this
/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.(com|edu|org)$/i
and it should become clear - you need to group those alternatives, otherwise you can match any string that has 'edu' in it, or any string that ends with org. To put it another way, your version matches any of these patterns
^[a-zA-Z0-9]+@[a-zA-Z0-9]\.(com)
(edu)
(org)$
It's worth pointing out that the original poster is using this as a regex learning exercise. This would be a terrible regex for actual production use! It's a thorny problem - see Using a regular expression to validate an email address for a lot more depth.
Your grouping parentheses are incorrect:
/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.(com|edu|org)$/i
Can also just use one case as you're using the i
modifier:
/^[a-z0-9]+@[a-z0-9]+\.(com|edu|org)$/i
N.B. you were also missing a +
from the second set, I assume this was just a typo...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With