Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

Combine regular expressions in JavaScript

My requirements are to allow a certain field to be 3-50 characters long, to contain alphanumeric and the '-' character, yet not allow 2 specific words.

I started with /^[\w\-\s]{3,50}$/. I then added /^((?!word1).)*$/i, /^((?!word2).)*$/i, etc.

I know that generally speaking, there's no logical AND for regexp. I can probably test the 3 regexs in a row, and fail if any of them fail, but I'd rather have a single regexp. What regular expression can I use to satisfy all 3 conditions?

Upvotes: 1

Views: 47

Answers (1)

anubhava
anubhava

Reputation: 784968

You can use this single regex using negative lookahead:

/^(?!.*?(word1|word2))[\w\s-]{3,50}$/i

Upvotes: 1

Related Questions