Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for phone number allowing 9 or 10 digits

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading