how to prepare regex have two conditions

Could you please tell me what will be the pattern when three same character not allowed I have a name field in which have few validations

  1. Name should not contain test "text"

I checked using indexOf .

  1. Name should not contain three consecutive charecters example "abc" , "pqr" ,"xyz"
    1. Name should not contain same character three times example "aaa" , "ccc" ,"zzz"

can we make a regex for it. I googled it not found

I tried like this

val ='a'
var phonenoRegex = /^a-zA-Z+$/;
if(val.toLowerCase().indexOf('test') !=-1&& phonenoRegex.test(val)){
}else {

1 answer

  • answered 2018-11-08 05:48 Barmar

    You can do all of this with alternatives in a regexp.

    if (/test|[^a-z]|(.)\1\1|abc|bcd|cde|def|...|wxy|xyz/i.test(val)) {
    } else {

    (.)\1\1 matches 3 repetitions of the same character; \1 is a back-reference to the character that the . matched. You test for consecutive letters by simply listing all of them as alternatives in the regexp (replace ... with all the missing ones that I skipped). You don't need toLowerCase() since the i option makes it case-insensitive.