Home > Software engineering >  Regex to validate 10 digit telephone number
Regex to validate 10 digit telephone number

Time:10-29

I have a usecase to validate a telephone number field, if a user enter all ten digit mobile number like (111)111-1111 / (999)999-9999, then we must show some error message to user.

Here I tried to validate this scenario with this regex \(([0-9])\1{2}\)\s\1{3}\-\1{4}$, it is validating if there are all unique numbers, but at the same time it’s giving error for a valid phone number which is not expected.

Please share your thoughts on this regex to validate this usecasae.

CodePudding user response:

The \s looks suspicious to me as there doesn't seem to be any whitespace in the phone number format you're trying to match.

Looks like you might be using python, and I'm not all that familiar with the nuances of \1 style group references. However, using plain regex I'd match the phone number format as follows:

\([0-9]{3}\)[0-9]{3}-[0-9]{4}

CodePudding user response:

Your pattern matches when all the digits are the same due to the capture group and the backreference.

What you can do is use your pattern in a negative lookahead assertion if that is supported, to make sure that your pattern does not occur directly to the right so that there is no match.

Then you can use the same pattern, but then match digits 0-9.

Note that in the example data, the \s which is in your pattern would not match.

^(?!\(([0-9])\1{2}\)\1{3}\-\1{4}$)\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
  • ^ Start of string
  • (?!\(([0-9])\1{2}\)\1{3}\-\1{4}$) Negative lookahead to assert not the pattern matching only the same digits to the right
  • \([0-9]{3}\)[0-9]{3}-[0-9]{4} If the assertion is true, the same pattern matching digits 0-9
  • $ End of string

Regex demo

  • Related