Easily Validate Zip Codes with the Zippopotamus Cloud API
September 12th, 2022 by Rijad HusicIn this blog post, we'll go over how to properly validate zip codes using the Zippopotamus Cloud API. This is particularly useful for e-commerce websites, where customers may accidentally enter the wrong zip code or even enter a fake one on purpose. By using an external service like Zippopotamus, we can easily and accurately validate zip codes without having to create our own database or put in the extra effort.
To get started, we'll need to have a form with a zip code input field. We'll also need to have a way to get the selected country and state from the form. In our example, we're using Magento 2 and have the following code to get this information:
var zipcode = $('#zip').val();
var country = $('#country option:selected').val();
var state = $('#state option:selected').val();
Next, we'll use the Zippopotamus API to validate the zip code. We'll do this by making an AJAX request to the API with the country and zip code, and then looping through the response to check if the state matches the selected state in the form. If the state does match, we'll set the result to true and return it. If not, we'll show an error message and return false. Here's the code that does this:
$(document).on('click', 'form button[type=submit]', function(e){
$("#zipcode_error").remove();
var zipcode = $('#zip').val();
var country= $('#country option:selected').val();
var state = $('#state option:selected').val();
var result = false;
var apiUrl = "https://api.zippopotam.us/" + country + '/' + zipcode;
$.ajax({
type: "GET",
url: apiUrl,
async: false,
success: function(data, status) {
if(data !== false){
var places = data.places;
places.forEach(function(place) {
var zipCodeState = place['state abbreviation'];
if (zipCodeState == state) {
result = true;
}
});
}
}
});
if (!result) {
$('#zip').after('
<div generated="true" id="zipcode_error" style="margin-top: 7px;color: #e02b27;font-size: 1.2rem;">Please select a zip code within your state</div>;');
}
return result;
});
That's it! By using the Zippopotamus API, we can easily and accurately validate zip codes on our website. This will help prevent mistakes by customers and make life easier for support staff.