How to validate a Phone Number in PHP
By the end of this article, you will have a system set up for automatic phone number validation based on syntax. The total process will only take about 5 minutes, so let’s get to it.
We will be using an API to accomplish our quick results, which will require installing our API client via this command.
composer require cloudmersive/cloudmersive_validate_api_client
After that’s done, our API will be accessible and we can call our phone number validation function, like so:
<?phprequire_once(__DIR__ . '/vendor/autoload.php');// Configure API key authorization: Apikey$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// $config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Apikey', 'Bearer');$apiInstance = new Swagger\Client\Api\PhoneNumberApi(// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.// This is optional, `GuzzleHttp\Client` will be used as default.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;}?>
Now all that’s left to do is input a phone number to test it out on. Yup, super easy. You might want to take a quick look at what else this API can do in the documentation section.
