custom phone number regex

Viewed 244

I am using regex ^(\+91|[0]?)\d{10}$ for phone number validation. I want below output.

+911234567891 - valid
01234567891 - valid
1234567891 - valid
0123456789 - should be invalid as I want 10 digits after 0.

Please suggest changes in regex pattern Thanks in advance

4 Answers

Your ^(\+91|[0]?)\d{10}$ pattern matches +91 or an optional 0 and then any 10 digits. That means any 10 digit string will pass the test. You need to make sure 10 digits are allowed after +91 or 0, or make sure the first digit is 1 to 9 and the rest is just 9 digits.

You may use

^(?:(?:\+91|0)\d{10}|[1-9]\d{9})$

See the regex demo.

Details

  • ^ - start of string
  • (?:(?:\+91|0)\d{10}|[1-9]\d{9}) - 2 alternatives:
    • (?:\+91|0)\d{10} - +91 or 0 and then any 10 digits
    • | - or
    • [1-9]\d{9} - a digit from 1 to 9 and then any 9 digits
  • $ - end of string.

Say for instance, in php - and javascript flavor you can use a possessive quantifier. Demo here. Code below:

^(\+91|0?+)\d{10}$

The change is replacing [0]? with 0?+. I removed the [...] for the sake of convenience. Then, the ?+ matches one 0 and won't let it go.

Another alternative is to list all the opportunities:

^(\+91\d{10}|0\d{10}|[1-9]\d{9})$

Demo here.

Only mistake in your regex is a misplaced question mark.

^(\+91|0)?\d{10}$

You can remove the square bracket around '0' as it is a single character.

/^([+]{0,1})([0]|[9][1]){0,1}([\d]{10})$/
Related