Formatting postal codes for US and Canada

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
        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);
        return true;
    if (sTmp.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/))
        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.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A Website.

Up ↑

%d bloggers like this: