how to prepare regex have two conditions

4087 views javascript
3

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)){
alert('false')
}else {
alert('true')
}

answered question

did you mean "pqr" in your second rule?

Name should not contain three consecutive charecters Then what sort of characters are allowed, other than alphabetical characters, if alphabetical characters can't occur three times in a row? Or, what do you mean?

yes "pqr" is not valid

@CertainPerformance He means it can't contain 3 consecutive letters that are consecutive in the alphabet, like abc or jkl.

@CertainPerformance I think you didn't understand my question

@Barmar yes ..that is correct

a-zA-Z needs to be in brackets [a-zA-Z]

@CertainPerformance He's converting to lowercase before doing any of the checks.

@Barmar He has phonenoRegex.test(val) so I'm not sure

@CertainPerformance aBc is also wrong

@CertainPerformance yes I will convert it on lower case sorry

@CertainPerformance That regexp has both upper and lower case in it, so it allows both.

1 Answer

10

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)) {
    alert('false');
} else {
    alert('true');
}

(.)\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.

posted this

Have an answer?

JD

Please login first before posting an answer.