Much like password validation, phone number validation is a frequent validation task in PHP. While there’s no way to validate that the number is an actual phone number (besides manually calling it), we can ensure that it looks like a valid number.
In data validation, ensuring that data looks like what you expect it to be is paramount. Let’s create a PHP function to validate phone numbers.
Creating A PHP Function To Validate Phone Numbers With PHP
Whether or not we use an input type=”text” or input type=”tel” with a regex pattern, users can still put in what they want or post directly to your processing script. You have to validate on the server side.
And, that’s where the problem with phone numbers lies. They can be formatted in so many different ways. So, how do we validate all of those different patterns?
Well, we can’t.
We just strip out the formatting characters and check the digit length.
A valid phone number for the US will contain at least 10 digits. If the country code is included, it could be more. Therefore, a valid phone number has a length of between 10 and 14 digits.
Example Of Function To Validate Phone Numbers
Here’s a function to validate phone numbers. We do a manual replacement of formatting characters. Another way to do it would be to preg_replace any character that is not a digit with nothing. I’ve used the following way for years and have never had an issue.
<?php
/**
* Scottsweb.dev
* Validate phone numbers
* Website: https://scottsweb.dev/validate-phone-numbers-with-php/
*/
/**
* Function validate_phone_number().
*
* Validates a phone number.
*
* @param string $phone - Phone number to be validated.
* @return bool - true on success, false on failure
*/
function validate_phone_number($phone) {
// replace formatting characters
$phone = str_replace(array('(', ')', ' ', '.', '+', '-'), '', $phone);
// what we have left should be numeric
if (!is_numeric($phone)) {
return false;
}
// and it should be between 10 and 14 digits in length
if (strlen($phone) < 10 || strlen($phone) > 14) {
return false;
}
// phone number appears good
return true;
}
Function To Validate Phone Numbers In PHP In Action
And here’s how to use the above function. Just call it by passing in a phone number string.
<?php
/**
* Example validate phone number
* Website: https://scottsweb.dev/validate-phone-numbers-with-php/
*/
// set a phone number statically. realistically, this would come from $_POST data
$phone_number = '123-456-7891';
// check if it's valid and echo a response
if (validate_phone_number($phone_number)) {
echo 'Phone number ' . $phone_number . ' is valid.';
} else {
echo 'Phone number ' . $phone_number . ' is not valid.';
}
More Data Validation
We also have articles/videos on How To Validate A Password and Creating A User Registration System. Check out those articles to further your skills.
If you enjoyed this video/article, please consider subscribing to scottsweb.dev on YouTube.