For the sake of standardizing the format for all system postal codes, I have implemented the following script to re-format the user input of postal codes for both US and Canada. The purpose is to take the user’s input, and re-arrange it to follow a standard format.

The comments are self-explanatory.

// Function to format postal code
// for both Canadian and US postal codes
function FormatPostalCode(context)
{
  var oField = context.getEventSource().getValue();
  var sTmp;
 
  if(typeof(oField) != "undefined" && oField != null)
  {
    // check for US ZIP code
    if(oField.match(/^[0-9]{5}$/))
    {
        context.getEventSource().setValue(oField);
        return true;
    }

    // check for Canadian postal code
    sTmp = oField.toUpperCase();
    if (sTmp.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/))
    {
        sTmp = sTmp.substr(0,3) + " " + sTmp.substr(3,3);
        context.getEventSource().setValue(sTmp);
        return true;
    }
    if (sTmp.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/))
    {
        context.getEventSource().setValue(sTmp);
        return true;
    }

    // alert("Incorrect ZIP/Postal Code format.");
    // postal code could be any other country, so leave as is
  }
}

Add the function in a Web Resource, and reference it on the postal code’s OnChange event. As the script uses the context, make sure you select the “Pass execution context as first parameter” option.

image

Enjoy!

Advertisements