Home > OS >  Regex for phone number allowing 9 or 10 digits
Regex for phone number allowing 9 or 10 digits

Time:11-26

I am trying to validate a regex which

  • allows 10 digits
  • if digit starts with 672 then it should only allow total 9 digits

I have tried below regex /^\d{10}$|^(672)\d{6}$/

https://regex101.com/r/0ahnKx/1

It works for 10 digits but if number starts with 672 then also it allows 10 digits. Could anyone help how can I fix this? Thanks!

CodePudding user response:

First of all, the capturing group in your regex is redundant, it would make sense to wrap the part of the pattern between ^ and $ to only use single occurrences of the anchors.

To fix the issue, you need to make sure the first three digits matched by \d{10} are not 672, and you can achieve that with a negative lookahead:

/^((?!672)\d{10}|672\d{6})$/
/^(?:(?!672)\d{10}|672\d{6})$/

See the regex demo. Details:

  • ^ - start of string
  • (?: - start of a group:
    • (?!672)\d{10} - no 672 substring check is triggered and then ten digits are matched
  • | - or
    • 672\d{6} - 672 and six digits
  • ) - end of the group
  • $ - end of string.
  • Related