Reikon
Reikon

Reputation: 43

Only matching when a string contains ALL characters specified in RegExp

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?

Upvotes: 0

Views: 125

Answers (1)

Ulysse BN
Ulysse BN

Reputation: 11423

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.

Upvotes: 1

Related Questions