Wednesday, November 30, 2011

Phone Number Validation using java script in CRM 2011

Hi All, Here is the logic to format Phone Number field into '(xxx) xxx-xxxx' format. It only allows user to enter only numeric characters, up to 10 char's.

function Bindevents() {
   // Binding the events to crm field, which needs to be validated
    crmForm.all.telephone1.onkeypress = isvalidPhone;
    crmForm.all.telephone1.onblur = function () { formatPhoneNumber("telephone1"); };
}




// Allows to enter only Numbers & upto 10 char's
function isvalidPhone() {
 
    var charCode = event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;


    var phnum = event.srcElement.value.replace(/[^0-9]/g, "");
    if (phnum.length >= 10)
         return false;


    return true;
}


// Formats Phone Number to '(xxx) xxx-xxxx' format
function formatPhoneNumber(phnum) {
 
    var phone = Xrm.Page.getAttribute(phnum).getValue();
    var tmp = phone.replace(/[^0-9]/g, "");
    phoneRegex = /^\d{10}$/;


    if (!tmp.match(phoneRegex)) {
            event.returnValue = false;        
            Xrm.Page.data.entity.attributes.get(phnum).controls.get(0).setFocus();
         
        }
        else {
            var formtedphn = "(" + tmp.substr(0, 3) + ") " + tmp.substr(3, 3) + "-" + tmp.substr(6, 4);
            Xrm.Page.getAttribute(phnum).setValue(formtedphn);
        }  
}

Hope it helps!!!!

1 comment:

  1. Use this telephone widget its awesome

    https://github.com/deep7686/telephone-widget

    ReplyDelete