How to Validate a Postal Code in PHP

Cloudmersive
1 min readApr 19, 2023

--

It’s important that new address information is correct before that data becomes available downstream in our application’s workflow.

Thankfully, we can easily validate postal codes with the free-to-use API provided below. A request containing a postal code, country name & country code will return a Boolean indicating if the postal value is valid, along with detailed latitude and longitude coordinates describing the location of the postal code in question. For example, making the following request:

{
"PostalCode": "94588",
"CountryFullName": "United States of America",
"CountryCode": "USA"
}

Will return the following response:

{
"ValidPostalCode": true,
"City": null,
"StateOrProvince": "California",
"Latitude": 37.6932951,
"Longitude": -121.925068362744
}

To structure our API call, we can begin by running the below command to install the client SDK:

composer require cloudmersive/cloudmersive_validate_api_client

After that, we can copy & paste from the ready-to-run code examples below to send information to the underlying service:

<?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\AddressApi(


new GuzzleHttp\Client(),
$config
);
$input = new \Swagger\Client\Model\ValidatePostalCodeRequest(); // \Swagger\Client\Model\ValidatePostalCodeRequest | Input parse request

try {
$result = $apiInstance->addressValidatePostalCode($input);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling AddressApi->addressValidatePostalCode: ', $e->getMessage(), PHP_EOL;
}
?>

We can authenticate our requests with a free-tier API key by registering a free account on the Cloudmersive website.

That’s all there is to it — no need to worry about invalid Postal Codes anymore!

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet