0

I have a problem with my regex. I didn't test this before. I have the following regex:

^(?:(?:[a-z])+(.|_)?(?!\.))*\w@(?:(?:[a-z])+(-|.)?(?!\.))*\w\.\w{2,}$

Now, my email validation halfly works. Here are some tests (according to regex101):

test -- invalid
test@ -- invalid
test@test -- invalid
test@test. -- invalid
[email protected] -- valid
[email protected]. -- invalid
test@[email protected] -- valid
[email protected] -- invalid

So, more than one @ can be used which is invalid for an email.

I kind of cannot see what I'm doing wrong.

NOTE:

I know there's a stackoverflow question that has a method on how to validate email with regex, HOWEVER: I'd like to know what I did wrong so I can learn from it.

3
  • 1
    Possible duplicate of Validate email address in JavaScript? Commented Mar 30, 2017 at 8:53
  • @AndyKorneyev I'd rather know what I did wrong so I can learn from it. Commented Mar 30, 2017 at 8:54
  • @MauricePerry Forgot to add a ,; my bad. Commented Mar 30, 2017 at 8:57

1 Answer 1

1

I found out the problem myself. The following regex does work:

^(?:(?:\w)+(\.|_)?(?!\.))*\w@(?:(?:[a-z])+(-|\.)?(?!\.))*[a-z]\.[a-z]{2,}$

I changed (.|_) into (\.|_) and (-|.) into (-|\.) to use . literally as a period and not as an 'all character "wildcard"'. I changed \w\.\w{2,} in [a-z]\.[a-z]{2,} to disallow _ in the last part.

Sign up to request clarification or add additional context in comments.

2 Comments

(\.|_) is better replaced with [._]. And no need escaping the dot then.
@WiktorStribiżew Thanks for the tip.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.