Search code examples
javascriptvalidationphone-number

Validating Phone Number based on country code


How to validate phone numbers based on country codes in Javascript.

For Example: India-starts with 91-xxxxxxxxxx, UK-44-xxxxxxxxxx, SZ-268-22xxxxxx and so on. Like this it should validate other countries country code with phone number which I will enter.

Below is the code which I tried but it is only for one country. Parallelly how to do validate with other countries country code.

function validateMobNo(mobno){
var mobno2;
var flag=false;
var mlen= mobno.length;
//alert(mobno.substr(3,mobno.length-3));
if(mobno.charAt(0)!='+' && mlen==10){
    mobno2="+91-"+mobno;
    alert("1>>your mobile wants to be in "+mobno2);
    flag=true;
}
else if(mobno.charAt(0)=='+'){
    if(mobno.substr(0,3)=='+91' && mobno.length==13){
        mobno2=mobno.substr(0,3)+"-"+mobno.substr(3,mobno.length-3);
        alert("2>>your mobile wants to be in "+mobno2);
        flag=true;      
    }
}
else if(mobno.indexOf("-")<0&&mobno.length==12 && mobno.substr(0,2)=='91'){
    mobno2=mobno.substr(0,2)+"-"+mobno.substr(3,mobno.length-2);
    alert("3>>your mobile wants to be in "+mobno2);
    flag=true;
    }
else
    alert("Please correct your mobile No");
if(flag==true)
   document.mobvalidate.mobno.value=mobno2;
else
    document.mobvalidate.mobno.focus()
return flag;

}

Solution

  • Using some method to loop over each country code and evaluates with regular erxpressions:

    country_codes=['91-', 'UK-44-', 'SZ-268-22']
    phone="91-123456789";
    
    is_valid_number = country_codes.some(elem => phone.match('^' + elem));
    console.log(is_valid_number );