Formatting postal codes

Working with postal codes is again left to the latitude of developers. With the wide range of countries supported, it would be unrealistic to try to provide the functionality out of the box.

Getting ready

Using the previously created solution or a new solution, we will add postal code formatting for the Account entity.

How to do it...

Take the following steps to format a postal code:

  1. Add a JScript web resource to hold your script.
  2. Add the following script to the resource:
    // 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;
      }
      
      // code is invalid
      // alert("Incorrect ZIP/Postal Code format.");
      // code could be any other country, so leave as is
      }
     }
  3. Add your function to the OnChange event of the postal code field you want to validate and format.
  4. Save and Publish your customizations.

How it works...

As with our previous example, we are reading the value based on the context we are passing, so we can reuse this function across multiple postal code fields on various forms.

Using regular expressions, we are validating that the format of the user input is either five numeric characters or a combination of six alternating characters as required for the Canadian postal code. This piece can easily be changed to map to any other country's postal code format.

The section commented out at the end allows us to notify the user if the postal code entered does not correspond to any of the required formats. We can take additional actions here, by either clearing the field using context.getEventSource().setValue(""); or just simply leaving the input as it is.

Alternatively you can use a web service to validate postal codes and addresses. Most international postal services will provide, for a price, a listing of all postal codes and associated addresses.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.216.160