D365 CRM: Formatting the Phone Number in US format using JavaScript



  • If you need to format a phone number field in an Entity Form in CRM, use the following JavaScript code to accomplish this:

        function formatFieldPhoneNumber(executionContext, fieldName) {
            formContext = executionContext.getFormContext();
            var value = formContext.getAttribute(fieldName).getValue();
            var phoneFormat = formatPhoneNumber(value);
         
            formContext.getAttribute(fieldName).setValue(phoneFormat);
        }
         
        let formatPhoneNumber = (str) => {
            //Filter only numbers from the input
            let cleaned = ('' + str).replace(/\D/g, '');
         
            //Check if the input is of correct
            let match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
         
            if (match) {
                //Remove the matched extension code
                //Change this to format for any country code.
                let intlCode = (match[1] ? '+1 ' : '')
                return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
            }
         
             return null;
        }

    Simple add the function “formatFieldPhoneNumber” in the OnChange event of your phone attribute field in the Form passing the execution context as a first parameter and the field name (telephone1 for ex.) as a second parameter and try it.
     
    Enjoy it!


  • Comments



Add a Comment