user3911183 user3911183 - 28 days ago 7
Javascript Question

Regex to block a phone number that contains same digit more than 4 times successively?

i would like to add a regex to check if a phone number contains the same digits more than n times.
this is what i tried :

^0[1-9]([-. ]?[0-9]{2}){4}$

how can i make it ?


You just need to check for any repeating character n times or more. First we need to determine which characters we want to catch. Second we need to get that single character from the capture group using the backslash + n. Finally we need to say how many times it should repeat from. In this scenario I don't think it needs to validate the entire number, just the fact there are the same repeated characters. So in order to catch any repeating number 4 or more times we can do:

'06000000000'.test(/([0-9])\1{3,}/); // return true
'12344445678'.test(/([0-9])\1{3,}/); // return true
'01234567890'.test(/([0-9])\1{3,}/); // return false

([0-9]) this is what we want to check, in this case any number from 0 to 9

\1 get the value from the first capture group

{3,} check this value is repeating 3 or more times, because we've already got that first character matched in our capture group. 3 + 1 = 4 naturally.