Formatting Telephone Numbers

Formatting Telephone Numbers

Telephone number fields in Microsoft Dynamics CRM do not include formatting for telephone numbers. To apply formatting, use a script in the OnChange event of the telephone number field. The following script applies basic formatting used for telephone numbers in the United States. This method supports 7-digit and 10-digit numbers, for example,  (410) 555-1212. In the code the expression ‘”4105551212″.length’ is equal to 10. Because the code references the event.srcElement, the same code can be used without modification in the OnChange event of any string field that displays a telephone number.

// Get the field that fired the event.
var oField = event.srcElement;

// Validate the field information.
if (typeof(oField) != "undefined" && oField != null)
{
 // Remove any non-numeric characters.
 var sTmp = oField.DataValue.replace(/[^0-9]/g, "");

 // If the number has a valid length, format the number.
 switch (sTmp.length)
 {
  case "4105551212".length:
  oField.DataValue = "(" + sTmp.substr(0, 3) + ") " +
  sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
  break;

  case "5551212".length:
  oField.DataValue = sTmp.substr(0, 3) + "-" +
  sTmp.substr(3, 4);
  break;
 }
}
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s