Wednesday, May 16, 2012

Formatting postal codes for USA for Dynamics CRM 2011

To Standardize & GUI Enhancement, I have implemented the following script to re-format the user input of postal codes for USA. Here I am collecting user’s input, and re-arranging it to follow a standard for zip code which is #####-####..
By default, Zip/Postal code field in Dynamics CRM is a free-form text field.  Requirement is that when a user types in a Zip Code like 432201234, it should automatically format the field to 43220-1234".
Dynamics CRM uses JavaScript for client side scripting and we can use Regular Expression to collect the data and match with the expression and if the format does not match then enforce to format. I am using (^\d{5}$)|(^\d{9}$)|(^\d{5}-\d{4}$) to match, whether user has typed in 5 characters or 9 characters or it is already in a US format Zip code like 43220-1234. If 5 then do not do anything, if 9, format it and if it is already in a US format Zip code like 43220-1234 do not do anything.

Now, follow the steps and screen shots.

1 - Create a web resource in CRM



2. Use the text editor to put the following JavaScript:
// Function to format Zip Code in USA Format XXXXX-XXXX
// Created by : Sudip Chakrovorty Dated : 5/15/2012
function FormatPostalCode(context)
{
var oField = context.getEventSource().getValue();
var tmp = oField;
    if(typeof(oField) != "undefined" && oField != null)
  {
    // check for US ZIP code format
    if(oField.match(/(^\d{5}$)|(^\d{9}$)|(^\d{5}-\d{4}$)/))
    {
        tmp = oField;
               
if(tmp.match(/^\d{9}$/))
    {
      tmp = tmp.substr(0,5) + "-" + tmp.substr(5,9);
      context.getEventSource().setValue(tmp);
      return true;
    }
}
else

    alert("Zip Code must contain 5 or 9 numbers.");
    //context.getEventSource().setValue("");
         }
}

3. Add your JavaScript into Form.



4 – Add a Reference of the Web resource in the field where you want to implement. Go to the properties of the field; Set the "form libraries" to above code. Then add an "event handler" for the Zip Code field's OnChange() event.   In the "function" field, use "FormatPostalCode".    Also, click on the "pass execution context as first parameter" check box.



And you are done.
Enjoy!

No comments:

Post a Comment

Power Automate Optimization: Filter Rows vs Trigger Conditions - When and Why to Use Each

Filter Rows vs Trigger Conditions in Power Automate Filter Rows vs Trigger Conditions in Power Automate Why your flow...