Phone number mask for Microsoft CRM 2011 using Javascript

By default, phone number fields in Microsoft CRM are free-form text fields. We wanted to enforce an edit mask so that when a user types in a US style phone number like 3031112222 it automatically formats the field to say "(303) 111-2222".

This code was built for Microsoft CRM 2011 Online version, but it should work for other versions.

Step 1 - Create a web resource in CRM with the following Javascript code:

Within CRM, go to Settings > Customizations > Customize the System > Web Resources.

function FormatPhoneNumber(context)

{

var oField = context.getEventSource().getValue();

var sTmp = oField;

if(typeof(oField)!= "undefined" && oField!= null)

{

sTmp = oField.replace(/[^0-9]/g, "");

switch (sTmp.length)

{

case 10:

sTmp = "(" + sTmp.substr(0,3) + ")" + " " + sTmp.substr(3,3) +"-" + sTmp.substr(6,4);

break;

default:

alert("Phone must contain 10 numbers.")

break;

}

}

context.getEventSource().setValue(sTmp);

}

In the hosted version of CRM, you have to copy the above code into Notepad and then save it with a ".js" extension so that you can upload this code.

Step 2 - In the field properties of the form field you want to use this code on:

a) Add a reference to the web resource you created in step 1 by going to the field's "form libraries" settings and referencing the above code.

b) Then add an "event handler" for the phone field's on change event. In the "function" field, use "FormatPhoneNumber". Also, click on the "pass execution context as first parameter" check box.