Search This Blog

Thursday, January 26, 2012

North American Formatting of Phone Numbers in CRM 2011

"Standardizing data entry" is often one of the top concerns our clients want their CRM solution to address. Creating a simili-input mask while still allowing users to enter additional notes when using an asterisk (*), here is code we use to help with the formatting of North American phone numbers.


Please note:
  • This code is for CRM 2011. If you're interested in our CRM 4.0 version, feel free to contact us and we'll gladly share it with you.
  • The function must be added to a web resource accessible to your form, and coupled with an onChange event on the phone number field itself. For example, the following would format the main phone field on the Account form >    function telephone1_onchange()
            {
                PhoneFormat("telephone1");
            }
  • We use the out-of-box address1_country field to determine if the phone number should or shouldn't be formatted. If you're using a custom field for the country, make sure to modify the code accordingly.

//------Format a 10-digit phone number to 'xxx xxx-xxxx', with the option to add stuff after the asteriskfunction PhoneFormat(oField) {
    var field = Xrm.Page.getAttribute(oField);
    if (field.getValue() != "undefined" && field.getValue() != null) {
        var country = Xrm.Page.getAttribute("address1_country").getValue();
        if (country == "Canada" || country == "United States" || country == "Bermuda" || country == "Mexico") {
            var sTmp = field.getValue().replace(/[^0-9,*]/g, "");
            if (sTmp.length == 10) {
                field.setValue(sTmp.substr(0, 3) + " " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4));
                field.setSubmitMode("always");
            }
            else {
                if (sTmp.length > 10) {
                    if (field.getValue().search(/[*]/g) > -1) {
                        field.setValue(sTmp.substr(0, 3) + " " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4) + " " + field.getValue().substring(field.getValue().search(/[*]/g)));
                    }
                    else {
                        field.setValue(sTmp.substr(0, 3) + " " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4) + " ext. " + sTmp.substring(10));
                    }
                }
                else {
                    if (Xrm.Page.context.getUserLcid() == 1033) {
                        alert("This number should contain 10 digits. Please verify the data entered.");
                    }
                    if (Xrm.Page.context.getUserLcid() == 1036) {
                        alert("Ce numéro devrait contenir 10 chiffres. Veuillez vérifier et faire les ajustements nécessaires.");
                    }
                }
            }
        }
    }
}