HOW TO FORMAT PHONE NUMBER IN DYNAMICS 365 USING JAVASCRIPT?

Scenario 1: User provides data into a phone number field and provides some special characters according to their format, which becomes a cumbersome task to clean them.

Scenario 2: User provides data into a phone number field and provides more than 10 characters.

Scenario 3: User provides data into a phone number field and the format provided is different by each user, which becomes a cumbersome task to clean them.


Solution: Using JavaScript we can achieve this 

              1. Clear all the special characters
                  var phoneNumber =
                  formContext.getAttribute(“telephone”).getValue();
                  phoneFormated = phoneNumber.replace(/[^0-9]/g, “”);

              2. Throws error for more than 10 digits 
                   if (phoneFormated.length !== 10)
                       {
                                    alert(“Phone number must contain 10 numbers.”);
                                    formContext.getControl(“telephone2”).setFocus();
                                    return false;
                        }

                 3. Format automatically based on a pre-defined template. E.g., (123) 456-7890
                      formContext.getAttribute(“telephone”).setValue(“(” + phoneFormated.substr(0, 3)
                      +”) ” + phoneFormated.substr(3, 3) + “-” + phoneFormated.substr(6, 4));

Leave a Reply