How to Validate a Postal Code, Receive Locational Information using JavaScript

Cloudmersive
2 min readAug 5, 2022

--

Invalid postal codes won’t get your website visitors anywhere. Thankfully, there’s an API for that. Our Postal Code Validation API will ensure the input code is correct & usable, and to prove the operation worked, it’ll return a string including the full country name & country code. Here’s a sample response JSON for your reference:

{
"PostalCode": "string",
"CountryFullName": "string",
"CountryCode": "string"
}

It’s easy to take advantage of this API for free — just register a free account on our website and use the API key you receive to authenticate access in the relevant code snippet below. The below JavaScript code examples are ready-to-run, so all you need to do is copy & paste and you’re good to go.

We can structure our API call using either the XHR feature in JavaScript, or by installing the jQuery library. If you go with the former, use the below snippet:

var data = JSON.stringify({
"PostalCode": "<string>",
"CountryFullName": "<string>",
"CountryCode": "<string>"
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://api.cloudmersive.com/validate/address/postal-code");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Apikey", "YOUR-API-KEY-HERE");
xhr.send(data);

If you go with the latter, first install the jQuery library with the below command:

bower install jquery

And then structure your API call using the below snippet:

var settings = {
"url": "https://api.cloudmersive.com/validate/address/postal-code",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json",
"Apikey": "YOUR-API-KEY-HERE"
},
"data": JSON.stringify({
"PostalCode": "<string>",
"CountryFullName": "<string>",
"CountryCode": "<string>"
}),
};
$.ajax(settings).done(function (response) {
console.log(response);
});

That’s it — you’re all done.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

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

No responses yet