How to Validate a City and State/Province Combination using JavaScript

When a visitor enters any type of information into your website, it’s important to make sure that information is valid. Otherwise, small errors like spelling mistakes can dilute the value of the information you’ve obtained. This is especially true when it comes to locational data — but thankfully, there’s an API for that. Our Validation API endpoint offers more than a dozen address/geolocation iterations; in this article, I’ll demonstrate how you can quickly & easily validate City and State/Province data by structuring an API call in JavaScript. You can use this API for free by registering a free account on our website, with a limit of 800 API calls per month.

Let’s begin by structuring our call using the XHR feature in JavaScript. You can do so by simply copying & pasting the below code snippet:

var data = JSON.stringify({
"City": "<string>",
"StateOrProvince": "<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/city");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Apikey", "YOUR-API-KEY-HERE");
xhr.send(data);

To instead use jQuery, first run the following installation command:

bower install jquery

Then use the following snippet to call the API:

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cloudmersive

Cloudmersive

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