2016-11-16 374 views
0

如何根據Javascript中的國家代碼驗證電話號碼。根據國家代碼驗證電話號碼

例如:印度 - 以91-xxxxxxxxxx,UK-44-xxxxxxxxxx,SZ-268-22xxxxxx等等開頭。像這樣,它應該驗證其他國家的國家代碼與我將輸入的電話號碼。

下面是我嘗試過的代碼,但它只適用於一個國家。同時如何與其他國家的國家代碼進行驗證。

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; 

} 
+0

最簡單的方法是有一個包含所有的正則表達式模式爲對象測試各國的電話號碼格式,並以國家代碼爲關鍵字。使用字符串操作會使它變得更加複雜和脆弱,比它需要的更多 –

+0

有人已經爲你做了這項工作[int-tel-input](https://github.com/ jackocnr/intl-tel-input)jQuery插件可以做到這一點。 –

+0

我以前用過這個庫。它有據可查。不要重新發明輪子。 https://github.com/googlei18n/libphonenumber – ppovoski

回答

1

使用some方法遍歷每個國家代碼,並定期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);

+0

正好在尋找類似這樣的代碼。謝謝 –