Tuesday, August 27, 2019

validate UK postcode using a free WebService in x++ Dynamics Ax 2012

in Uk there is this free service http://postcodes.io/ which can be used to validate a uk postcode.

here an example on how to use it in x++ using a Web Service and parse the returned Json

static void JobEF_WebServiceTestInDialog(Args _args)
{
    Dialog dialog;
    DialogField zipCodeField;
    LogisticsAddressZipCodeId postcode;
    str result = '"result":';
    str postcodeServiceUri = 'http://api.postcodes.io/postcodes/%1/validate';
    str values, ret;
    int ptr, len;
    System.Net.WebClient webclient;
    str uri;
    NoYesId validPostCode;
    
    webclient = new System.Net.WebClient();
    
    dialog = new Dialog('Validate UK postcode using Web Service');
    
    zipCodeField = dialog.addField(ExtendedTypeStr(LogisticsAddressZipCodeId));
    
    if (dialog.run())
    {
        postcode = zipCodeField.value();
        if (!postcode)
        {
            warning('please select a post code');
            return;
        }
        
        uri = strfmt(postcodeServiceUri, postcode);
        
        // Get the value from the server given the URL.
        values = webclient.DownloadString(uri);

        // Find the result value from the JSON
        len = strLen(values);
        ptr = strScan(values, result, 1, len);
        ret = subStr(values, ptr + strLen(result), len - ptr - strLen(result));
        validPostCode = ret == 'true';
        
        info(strFmt('"%1" is %2', postcode, validPostCode ? 'a valid postcode' : 'an invalid postcode'));
    }
}

No comments:

Post a Comment