Validate Input Phone Number in Microsoft Dynamics CRM using JavaScript

Sometime we get requirement to validate a phone number like to check only numeric value allowed with all round bracket and '+' sign etc in the number. So below is a basic JavaScript fucntion which validates a phone number like: (022)6655-7878 or +91-7878787878 or +44-6756-6767-4234 and so on

function CheckPhoneNoFormat(context) {
    var oField = context.getEventSource().getValue();
    if (typeof (oField) != "undefined" && oField != null) {
        try {
            var telnum = oField;

            // Convert into a string and check that we were provided with something
            var telnum = telnum + " ";
            if (telnum.length == 1) {
                telNumberErrorNo = 1;
                return false
            }
            telnum.length = telnum.length - 1;

            // Remove spaces from the telephone number to help validation
            while (telnum.indexOf(" ") != -1) {
                telnum = telnum.slice(0, telnum.indexOf(" ")) + telnum.slice(telnum.indexOf(" ") + 1)
            }

            // Remove hyphens from the telephone number to help validation
            while (telnum.indexOf("-") != -1) {
                telnum = telnum.slice(0, telnum.indexOf("-")) + telnum.slice(telnum.indexOf("-") + 1)
            }

            // Remove hyphens from the telephone number to help validation
            while (telnum.indexOf(")") != -1) {
                telnum = telnum.slice(0, telnum.indexOf(")")) + telnum.slice(telnum.indexOf(")") + 1)
            }

            while (telnum.indexOf("(") != -1) {
                telnum = telnum.slice(0, telnum.indexOf("(")) + telnum.slice(telnum.indexOf("(") + 1)
            }

            while (telnum.indexOf("+") != -1) {
                telnum = telnum.slice(0, telnum.indexOf("+")) + telnum.slice(telnum.indexOf("+") + 1)
            }

            var phoneRegex = telnum.replace(/[^0-9]/g, "");

            if (phoneRegex.length == telnum.length) {
                context.getEventSource().setValue(oField);
                return true;
            }

            else {
                alert("Invalid Number. Please Enter Again");
                context.getEventSource().setValue('');
                return false;
            }
        }
        catch (err) { alert("Some Error Occured. " + err); return false; }
    }
}

Comments

  1. nice blog
    https://prudvihub.blogspot.com/

    ReplyDelete

Post a comment

Popular posts from this blog

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

Dumps for Microsoft Dynamics CRM MB2-703 Practice Exam Questions Free

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

Show GridView row details in tooltip on mouseover with jQuery using asp.net inside GridView in c#

go to top image