0

I'm trying to apply a data validation formula to a column, checking if the content is a valid international telephone number. The problem is I can't have +1 or +some dial code because it's interpreted as an operator. So I'm looking for a regex that accepts all these, with the dial code in parentheses:

(+1)-234-567-8901
(+61)-234-567-89-01
(+46)-234 5678901
(+1) (234) 56 89 901
(+1) (234) 56-89 901
(+46).234.567.8901
(+1)/234/567/8901

A starting regex can be this one (where I also took the examples).

Community
  • 1
  • 1
MultiformeIngegno
  • 6,959
  • 15
  • 60
  • 119

1 Answers1

0

This regex match all the example you gave us (tested with https://fr.functions-online.com/preg_match_all.html)

/^\(\+\d+\)[\/\. \-]\(?\d{3}\)?[\/\. \-][\d\- \.\/]{7,11}$/m
  1. ^ Match the beginning of the string or new line.

  2. To match (+1) and (+61): \(\+\d+\): The plus sign and the parentheses have to be escaped since they have special meaning in the regex. \d+ Stand for any digit (\d) character and the plus means one or more (the plus could be replaced by {1,2})

  3. [\/\. \-] This match dot, space, slash and hyphen exactly one time.

  4. \(?\d{3}\)?: The question mark is for optional parenthesis (? = 0 or 1 time). It expect three digits.

  5. [\/\. \-] Same as step 3

  6. [\d\- \.\/]{7,11}: Expect digits, hyphen, space, dot or slash between 7 and 11 time.

  7. $ Match the end of the line or the end of the string

  8. The m modifier allow the caret (^) and dollar sign ($) combination to match line break. Remove that if you want those symbol to match only the begining and the end of the string.

  9. Slashes are use are delimiter for this regex (there are other character that you can use).

I must admit I don't like the last part of the regex as do not ensure that you have at least 7 digits.

It would be probably better to remove all the separator (by example with PHP function str_replace) and deal only with parenthesis and number with this regex

/(\(\+\d+\))(\(?\d{3}\)?)(\d{3})(\d{4})/m

Notice that in this last regex I used 4 capturing group to match the four digit section of the phone number. This regex keep the parenthesis and the plus sign of the first group and the optional parenthesis of the second group. To keep only the digits group, you can use this regex:

/\(\+(\d+)\)\(?(\d{3})\)?(\d{3})(\d{4})/m

Note: The groups are for formatting the phone number after validating it. It is probably better for you to keep all your phone number in your database in the same format.

Well, here are different possibility you can use.

Note: Those regex should be compatible with all regex engine, but it is good practice to specify with which language you works because regex engine don't deal the same way with advanced/fancy function.

By example, the look behind is not supported by javascript and .Net allow a more powerful control on lookbehind than PHP.

Keep me in touch if you need more information