Australian Postcode Client Script Validation
//Get Field Objects
const billingStateField = ZDK.Page.getField('Billing_State');
const billingCodeField = ZDK.Page.getField('Billing_Code');
//Get Field Values
const billingState = billingStateField.getValue();
const billingCode = billingCodeField.getValue();
//Get API Key from CRM Variables
if (billingState && billingCode) {
//Check the postcode is 4 numbers with a RegEx
const postcodeRegex = /^\d{4}$/;
if (postcodeRegex.test(billingCode))
{
const fetchApiKey = ZDK.Apps.CRM.Settings.fetchVariablesById('6040139000001156675');
let apiKey = fetchApiKey.value;
//Call Auspost API
auspostQuery = ZDK.HTTP.request({
url: 'https://digitalapi.auspost.com.au/postcode/search.json',
method: 'GET',
parameters: {
'q': billingCode,
'state': billingState
},
headers: {
'auth-key': apiKey
}
});
//Get the API Response Status
let auspostStatus = auspostQuery.getStatusCode();;
//Get the API Response
let auspostResponse = auspostQuery.getResponse();
//Only continue if a 200 status is returned
if (auspostStatus === 200) {
let auspostData = JSON.parse(auspostResponse);
let suburbList = auspostData.localities.locality;
//API returns either null/undefined || Object || Array based on number of suburbs.
//null / undefined
if (suburbList && suburbList !== null) {
//If object create Array
if (!Array.isArray(suburbList)) {
suburbList = [suburbList];
}
//Check there is at least 1 object in the Array
if (suburbList.length > 0) {
//check for a match
const matchFound = suburbList.some(suburb => suburb.state === billingState && suburb.postcode == billingCode);
if (matchFound) {
return true;
}
}
else {
billingCodeField.showError('Postcode does not belong to this State.');
return false;
}
}
else {
billingCodeField.showError('Postcode does not belong to this State.');
return false;
}
}
else {
let errorMessage = JSON.parse(auspostResponse).error.errorMessage
ZDK.Client.showAlert('An Error Occured: ' + errorMessage, 'Notice', 'Got it!');
}
}
else
{
billingCodeField.showError('Postcode must be a 4 digit number.');
return false;
}
}
else if (!billingState && billingCode)
{
billingStateField.showError('Please Enter a State Value in the format: NSW, VIC, SA');
return false;
}
else if (billingState && !billingCode)
{
billingCodeField.showError('Please Enter a Postcode.');
return false;
}
return true