Validating for Digits Only

Let's start with a basic PHP function to validate whether our input telephone number is digits only. We can then use our isDigits function to further refine our phone number validation.

We use the PHP preg_match function to validate the given telephone number using the regular expression:


This regular expression checks that the string $s parameter only contains digits [0-9] and has a minimum length $minDigits and a maximum length $maxDigits. You can find detailed information about the preg_match function in the PHP manual.

Checking for Special Characters

Next, we can check for special characters to cater for telephone numbers containing periods, spaces, hyphens and brackets .-(). This will cater for telephone numbers like:

  • (012) 345 6789
  • 987-654-3210
  • 012.345.6789
  • 987 654 3210

The function isValidTelephoneNumber removes the special characters .-() then checks if we are left with digits only that has a minimum and maximum count of digits.

International Format

Our final validation is to cater for phone numbers in international format. We'll update our isValidTelephoneNumber function to look for the + symbol. Our updated function will cater for numbers like:

  • +012 345 6789
  • +987-654-3210
  • +012.345.6789
  • +987 654 3210

The regular expression:


tests whether the given telephone number starts with + and is followed by any digit [0-9]. If it passes that condition, we remove the + symbol and continue with the function as before.

Our final step is to normalize our telephone numbers so we can save all of them in the same format.

Key Takeaways

  • Our code validates telephone numbers is various formats: numbers with spaces, hyphens and dots. We also considered numbers in international format.
  • The validation code is lenient i.e: numbers with extra punctuation like 012.345-6789 will pass validation.
  • Our normalize function removes extra punctuation but wont add a + symbol to our number if it doesn't have it.
  • You could update the validation function to be strict and update the normalize function to add the + symbol if desired.