Regex:
^(\(?([\d \-\)\–\+\/\(.]+){8}\)?([ .\-–\/]?)([\d]+))$
Goal:
- Supports North America AND International Phone Numbers
- Users filling our forms know we are in Canada, MAY or MAY NOT enter their country code, but are being askek for their country if requirred, so no forcing of country code in the phone number
- Users MAY or MAY NOT know how to dial long distance or international from Canada, so no forcing to enter "+" or 00 or 011 neither
- Phone number does not include EXT - our form has another simple digit field for office extensions
- Minimum length is 9 digits set by {8} (does Australia or others still using 6 digits number?)
Based on https://regexpattern.com/phone-number/, this is the german regex I adapted :
Match those numbers : (tested on https://regex101.com/r/BwjY50/1 and https://ihateregex.io/expr/
US (North American) Phone Numbers
1-800-123-4567
(123)456-7890
1234567890
123-456-7890
123.456.7890
123 456 7890
(123) 456 7890
UK Phone Numbers
+447222555555
+44 7222 555 555
(0722) 5555555 #2222(no match)
French Phone Numbers
0123456789
01 23 45 67 89
01.23.45.67.89
0123 45.67.89
0033 123-456-789
+33-1.23.45.67.89
+33 – 123 456 789
+33(0) 123 456 789
+33 (0)123 45 67 89
+33 (0)1 2345-6789
+33(0) – 123456789
German Phone Numbers
(06442) 3933023
(02852) 5996-0
(042) 1818 87 9919
06442 / 3893023
06442 / 38 93 02 3
06442/3839023
042/ 88 17 890 0
+49 221 549144 – 79
+49 221 – 542194 79
+49 (221) – 542944 79
0 52 22 – 9 50 93 10
+49(0)121-79536 – 77
+49(0)2221-39938-113
+49 (0) 1739 906-44
+49 (173) 1799 806-44
0214154914479
02141 54 91 44 79
01517953677
+491517953677
015777953677
02162 – 54 91 44 79
(02162) 54 91 44 79
Chinese Phone Numbers
0936-4211235
89076543
010-12345678-1234
Chinese Mobile Phone Numbers
008618311006933
+8617888829981
1911925564
India Phone Numbers
03595-259506
03592 245902
03598245785
9775876662
0 9754845789
0-9778545896
+91 9456211568
91 9857842356
919578965389
Brazilian Phone Numbers
(12) 123 1234
(01512) 123 1234
(0xx12) 1234 1234
Australian Phone Numbers
0732105432
1300333444
6 digits really? minimum requirred in this regex is currently set with {8}
131313(no match)
Dutch Phone Numbers
+31235256677
+31(0)235256677
023-5256677
Sweden Phone Numbers
+46 8 123 456 78
08-123 456 78
0123-456 78
It works! Looking for flaws or valid unsupported numbers.
Your solution is good enough for simple cases, but it fails on many edge cases. For example, there is plenty of invalid phone numbers passing the check, such as:
You may even be able to account for some of these, like parenthesis balancing, but coming up with a single regex that accounts for all the possible cases I think is difficult, and it would for sure make it hard to maintain.
You may consider forcing the users to at least "hints" you about the country or format in which they intend to insert the number, and use this information to match against simpler, more "specialized", regexes.