Feb 7, 2013

Telephone number formatting in US style

I just came across a requirement of formatting phone number in US style while displaying and remove it while saving. It also check if the ten digits are present in the value entered in telephone field textbox. It just take the consecutive 10 digits and format if based on US phone style. It can be achieved using JavaScript and regular expression as below

//Summary -it would apply formatting to phone fields
//Execution - on field change
function formatPhoneOnChange(executionContext) {
var attribute = executionContext.getEventSource();
var fieldName = attribute.getName();

//All Phone fields – specify all field which require formatting here
var phoneFields = ["telephone1"]
//Summary -this would apply formating for all fields specified in array
//Execution - On Form Load
function applyFormatingToPhoneFields() {
for (var i = 0; i < phoneFields.length; i++) {

//Summary - this would remove formatting for all fields specified in arrary
//Execution - On Form Save
function removeFormattingOfPhoneFields() {
for (var i = 0; i < phoneFields.length; i++) {

//Summary -it would apply formatting by field name
function formatPhone(fieldName) {
var phone = Xrm.Page.getAttribute(fieldName).getValue().replace("(", "").replace(")", "").replace("-", "").replace(" ", "");
if (new String(phone.match(/\d{10}/)).length == 10) {
Xrm.Page.getAttribute(fieldName).setValue(phone.match(/\d{10}/).toString().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3").toString());
else {


No comments: