user1829169
user1829169

Reputation: 33

custom phone number regex

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

Upvotes: 3

Views: 294

Answers (4)

Gor Grigoryan
Gor Grigoryan

Reputation: 1

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

Upvotes: 0

soumya sunny
soumya sunny

Reputation: 226

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.

Upvotes: 0

Tamas Rev
Tamas Rev

Reputation: 7166

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.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627119

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.

Upvotes: 3

Related Questions