Microsoft Dynamics + Javascript Phone Numbers

We run Microsoft Dynamics 365 CRM at work and I’m trying to get our 3CX phone system to do phone number lookup against it. Unfortunately users are putting all sorts in the 3 phone number fields we run, including cutting & pasting from other sources.

I wanted some way of just making it easy to end up with the number in E.164 format as the input mask options offered on the forms don’t give this ability.

Since I haven’t written any Javascript inside of Dynamics I really struggled to find any good basic tutorials to get it up and running.

The trick appears to be to create a new solution and add your JavaScript to that as a Web Resource. Then “Add Existing” entities; in my case I added the Account and the forms I would be checking the OnChange event of a field.

In the form properties, under Events, add the new piece of script as a Form Library and in the properties of the field under Events, Event Handlers add the library to the OnChange Event.

One of the best bits of documentation I referenced is here as it showed how to check off the “pass execution context as first parameter” as shown.

function formatPhoneNumber(context) {
    //Establish which of the 3 phone numbers changed and get its name.
    var phone = context.getEventSource().getName(); 
    var phoneNumber = Xrm.Page.getAttribute(phone).getValue();
    if (phoneNumber == null)
        return true;
    //strip everything out apart from digits. Regex FTW.
    var fixedNumber = phoneNumber.replace(/[^0-9]/g, ''); 
    //check for NZ number
    var regex = /^0([2-9]\d{7,9})/g;  
    if ( >= 0 ){
        fixedNumber = fixedNumber.replace(regex, '64$1');
    // Then add the plus symbol back for E.164 compliance.
    fixedNumber = "+" + fixedNumber;
    // Set the field to the newly formatted and fixed number
    return true;