Dreams
Dreams

Reputation: 8506

Validate phone number start with 0 and must be 8 or 9 or 10 digits

Below is my regex pattern..

/^0[0-9]\d{8}$/g

This pattern will allow any number start with 0 and must have 8 digits.

However, what I need is start with 0 and must have 8 or 9 or digits.

How to do that?

Upvotes: 0

Views: 18194

Answers (1)

timolawl
timolawl

Reputation: 5564

You don't need to have the [0-9] as \d does the same thing. I have laid out solutions depending on your exact request as you seem to have two different requests. Is it 8 to 9 digits or 8 to 10 digits, and does this total include the initial 0? See below for solutions to both:

Case 1:

must be 8 or 9 or 10 digits

Try:

/^0\d{7,9}$/ // or /^0\d{8,10}$/ if not including the initial 0 in the count

Case 2:

start with 0 and must have 8 or 9 or digits.

Try:

/^0\d{8,9}$/ // if the 8 or 9 digits does not include the initial 0 for the count
/^0\d{7,8}$/ // if the 8 or 9 digits does include the initial 0 for the count

Details:

{8,9} specifies matching 8 or 9 characters of the preceding token.

If the total number of digits includes the initial 0, then simply replace {8,9} with {7,8} (that way the total number of digits is 8 or 9). If you want the range to be 8 to 10, as mentioned in the title, then instead of {8,9}, use {8,10}. Again, this would be {7,9} instead if not accounting for the initial 0.

Regex101

Upvotes: 3

Related Questions