簡體   English   中英

使用libphonenumber在不知道國家的情況下驗證手機號碼

[英]Use libphonenumber to validate mobile phone number without knowing the country

我有來自任何國家/地區的電話號碼列表(字符串)。

例如:

var items = new List<string> { "+989302794433", "009891234599882", "+391234567890", "00336615551212"};

起初,我認為每個國家/地區代碼長度正好是兩個數字,例如(33:法國,39:意大利,98:伊朗,...)。

使用libphonenumber庫,您必須通過 regCode 進行解析。 並且因為(在我的場景中)我得到了字符串列表(手機號碼),那么我必須將國家代碼與號碼分開。

       foreach (var item in items)
        {
            int countryCode = 0;
            var number = "";

            if (item.StartsWith("+"))
            {
                countryCode = int.Parse(item.Substring(1, 2));
                number = item.Substring(3);
            }
            else if (item.StartsWith("00"))
            {
                countryCode = int.Parse(item.Substring(2, 2));
                number = item.Substring(4);
            }
           var regCode = phoneUtil.GetRegionCodeForCountryCode(countryCode);

            var numberWithRegCode = phoneUtil.Parse(number, regCode);

            if (!phoneUtil.IsValidNumber(numberWithRegCode)) continue;
            //else ...
        }  

此代碼僅適用於長度為兩個數字的國家/地區代碼!

但是過了一會兒,我知道某些國家/地區代碼長度是一個數字(例如,美國:1)甚至三個數字!。

現在,是否存在使用libphonenumber庫(或其他解決方案)來解決此問題的任何方法?

非常感謝

只要數字以 + 開頭,libphonenumber 庫就可以自行查找國家/地區代碼。 因此,只需用加號替換數字開頭的雙零即可。 然后讓圖書館自行決定號碼是否有效。

libphonenumber 將自行知道加號后面的國家代碼是哪個(它內部有所有代碼的列表),然后根據正確的國家/地區應用規則來確定該號碼是否有效。

bool IsValidNumber(string aNumber)
{
    bool result = false;

    aNumber = aNumber.Trim();

    if (aNumber.StartsWith("00"))
    {
        // Replace 00 at beginning with +
        aNumber = "+" + aNumber.Remove(0, 2);
    }

    try
    {
        result = PhoneNumberUtil.Instance.Parse(aNumber, "").IsValidNumber;
    }
    catch
    {
        // Exception means is no valid number
    }

    return result; 
}

您可以使用此包的日期https://www.npmjs.com/package/dialcodes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM