How to Validate Phone Numbers in PHP
Using the free API provided in this article, you can easily validate phone number inputs in your application with minimal code. The underlying service will analyze the syntax of each phone number relative to its country code, determine its validity & type, and subsequently return the phone number in E164, international and national formats. For example, the following sample input:
{
"PhoneNumber": "1.555.737.3810",
"DefaultCountryCode": "US"
}
Will return the following output:
{
"IsValid": true,
"Successful": true,
"PhoneNumberType": "FixedLineOrMobile",
"E164Format": "+15087373810",
"InternationalFormat": "+1 508-737-3810",
"NationalFormat": "(508) 737-3810",
"CountryCode": "US",
"CountryName": "United States"
}
To take advantage of this API, you’ll first need to grab a free-tier API key (register a free account on the Cloudmersive website to get one). After that, you can run the following command to install the client SDK:
composer require cloudmersive/cloudmersive_validate_api_client
And use the below code to structure your API call:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\PhoneNumberApi(
new GuzzleHttp\Client(),
$config
);
$value = new \Swagger\Client\Model\PhoneNumberValidateRequest(); // \Swagger\Client\Model\PhoneNumberValidateRequest | Phone number to validate in a PhoneNumberValidateRequest object. Try a phone number such as \"1.800.463.3339\", and either leave DefaultCountryCode blank or use \"US\".
try {
$result = $apiInstance->phoneNumberSyntaxOnly($value);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling PhoneNumberApi->phoneNumberSyntaxOnly: ', $e->getMessage(), PHP_EOL;
}
?>
That’s all there is to it — no more code required!