Posted on 10/25/2016 5:43:00 PM by Levin, Aric

Dynamics CRM 

The telephone fields in account, contact and lead entities do not really come with any formatting rules for particular countries. The phone field format setting might resolve some issues, but not all of them.

Let’s take the following scenarios of users entering phone numbers:

Input Value Output Value 
1234567123-4567
444 555 6789(444) 555-6789
1-800-434-5454(800) 434-5454

 

In order to resolve this issue we first get remove all of the non-numeric characters. This logic might require if you want to support extensions. Once we remove the non-numeric characters, we need to check the length of the phone number and apply our business rules based on that.

The following JavaScript code takes care of this situation:

function formatPhoneNumber()
{
    var phoneNumber = Xrm.Page.getAttribute("telephone1").getValue()
    var fixedNumber = string.replace(/[^0-9]/g, '');

    var output = "";
    switch (fixedNumber.length)
    {
        case 7:
            output = fixedNumber.substring(0, 3) + "-" + fixedNumber.substring(4, 7);
            break;
        case 10:
            output = "(" + fixedNumber.substring(0, 3) + ") " + fixedNumber.substring(4, 6) + "-" + fixedNumber.substring(7, 10);
            break;
        case 11:
            if (fixedNumber.substring(0, 1) == "1")
                output = "(" + fixedNumber.substring(1, 4) + ") " + fixedNumber.substring(5, 7) + " " + fixedNumber.substring(8, 11);
            else
                output = fixedNumber;
            break;
        default:
            // Error No Output
            output = phoneNumber
            break;
    }
    Xrm.Page.getAttribute("telephone1").setValue(output);
}

 

You can modify the code above to accept the name of the field instead of hard coding it, so that the same logic can be applied to multiple controls

function formatPhoneNumber(fieldName)
{
    var phoneNumber = Xrm.Page.getAttribute(fieldName).getValue()

    // Phone Number formatting logic comes here
    Xrm.Page.getAttribute(fieldName).setValue(output);
}

Navigate to original post to enter comments