3

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 Answers4

3

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

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.

Tamas Rev
  • 7,008
  • 5
  • 32
  • 49
0

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.

soumya sunny
  • 226
  • 1
  • 7
0
/^([+]{0,1})([0]|[9][1]){0,1}([\d]{10})$/
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Nov 27 '20 at 12:26