0

I'm trying to build a simple validator that will match [email protected] but not John@gmailcom or Johngmail.com - it must contain both @ and .

I am using this - /[@.]/g but it matches and tests when only one of these characters are matched.

Is there a better method of doing this?

6
  • Not the final solution, but one step closer : ^[[email protected]]{14}$ (I assumed chars can be shuffled because else that would be a strict equality withtout the neeed of a regexp) Commented Jan 22, 2020 at 15:45
  • positive lookahead /(?=.*@.*\.).+/g Commented Jan 22, 2020 at 15:46
  • If '@' followed by dot is the only check you perform for valid e-mail, @. happen to be valid e-mail either. Commented Jan 22, 2020 at 15:47
  • @UlysseBN I can admit it's only a partial answer but how is that friendly or unfriendly ? By the way, when I talk about what I see, you talk about what you assume is in the mind of someone else, please check yourself about friendlyness. Commented Jan 22, 2020 at 16:07
  • @challet I'm really confused. I definitely thought your comment was ment as a joke, seeing that you forced the check on any character included in [email protected], fourteen times, when OP was only talking about @ and .. And your explanation wasn't there as well. I'll just remove my comment, sorry for the trouble. Commented Jan 22, 2020 at 16:22

1 Answer 1

1

The issue with your regexp is that [] will tell whether one of @ or . is present.

If order matters, and you want @ to preceed ., you could use:

@.*\.

This will match any string that has @ and . with any character between them.

If order doesn't matter, I guess there is really no need for a Regexp:

myString.includes('@') && myString.includes('.')

The regexp version is available on regex101 so you can see details.

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

3 Comments

@MonkeyZeus you are definitely right, and I guess it would be hard for a regexp to not care about order. Except with a trick like sorting the string before. I'll just delete this bit :)
@MonkeyZeus you should read again my answer... OP didn't ask for @ to preceed ., hence my proposition is saying if order matters and if order doesn't matter. If OP wanted a real email validation, there are a lot more parameters to take into account anyway.
@UlysseBN- thanks, totally fixed the issue. Basic error from my end! Has to be a regex I think as I'm using data from an external source that will change, so for futureproofing it needs to handle more then just emails. After implementing what you suggested it now works on other stuff too. Thanks!

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.