Developer
Developer

Reputation: 1040

Phone number validation REGEX

I am using the following REGEX for validating phone numbers

/^(?!([^-]*-){5})(\+\d+)?\s*(\(\d+\))?[- \d]+$/gi

If the input is suppose +51 (0) 989009890 it is valid. But when the input is 0051 (0) 989009890. I am new to REGEX so couldnot find a possible solution.

Phone numbers are valid if it is of the following formats.

  1. 0xxxxxxxxxxx
  2. +xx xxxxxxxxxxx
  3. +xxxxxxxxxxxxx
  4. +xx (x) xxxxxxxxxx
  5. 00xxxxxxxxxx
  6. 00xx (x) xxxxxxxxx

here x denotes numbers 0-9. numbers inside () has limit upto 3.

Upvotes: 0

Views: 774

Answers (2)

Anirudha
Anirudha

Reputation: 32797

I guess this is what you are looking for

^(?!([^-]*-){5,})(\+?\d+)?\s*(\(\d{1,3}\))?\s*[- \d]+$

Upvotes: 1

femtoRgon
femtoRgon

Reputation: 33341

If you mean to accept 0051 (0) 989009890 as well, the problem is (+\d+)? is meant to handle the bit before the parentheses in the input, but it requires a '+' to be present. You could change that by making it optional with a '?', like:

/^(?!([^-]*-){5})(\+?\d+)?\s*(\(\d+\))?[- \d]+$/gi

Or, if '00xxx' should be an alternative to '+xxx' (that is, either a '+' or '00' must be present there), then you could use:

/^(?!([^-]*-){5})(\+\d+|00\d+)?\s*(\(\d+\))?[- \d]+$/gi

Upvotes: 2

Related Questions