Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phone regex validation for Argentina

I figured out a regular expresion for my country's phone but I've something missing.

The rule here is: (Area Code) Prefix - Sufix

  • Area Code could be 3 to 5 digits
  • Prefix could be 2 to 4 digits.
  • Area Code + Prefix is 7 digits long.
  • Sufix is always 4 digits long
  • Total digits are 11.

I figured I could have 3 simple regex chained with an OR "|" like this:

/(\(?\d{3}\)?[- .]?\d{4}[- .]?\d\d\d\d)|(\(?\d{4}\)?[- .]?\d{3}[- .]?\d\d\d\d)|(\(?\d{5}\)?[- .]?\d{2}[- .]?\d\d\d\d)/

The thing I'm doing wrong is that \d\d\d\d doesn't match only 4 digits for the sufix, for example: (011) 4740-5000 which is a valid phone number, works ok but if put extra digits it will also return as a valid phone number, ie: (011) 4740-5000000000

like image 662
Pablo Fernandez Stearns Avatar asked Oct 31 '22 18:10

Pablo Fernandez Stearns


1 Answers

You should use ^ and $ to match whole string

For example ^\d{4}$ will match exactly 4 digits not more not less.

Here is the complete regex pattern

^((\(?\d{3}\)? \d{4})|(\(?\d{4}\)? \d{3})|(\(?\d{5}\)? \d{2}))-\d{4}$

Online demo


As per your regex pattern delimiter can be -,. or single space then try

^((\(?\d{3}\)?[-. ]?\d{4})|(\(?\d{4}\)?[-. ]?\d{3})|(\(?\d{5}\)?[-. ]?\d{2}))[-. ]?\d{4}$
like image 125
Braj Avatar answered Nov 15 '22 12:11

Braj