【问题标题】:Use libphonenumber to validate mobile phone number without knowing the country在不知道国家的情况下使用libphonenumber验证手机号码
【发布时间】:2016-10-05 15:42:41
【问题描述】:

我有一个来自任何国家的电话号码列表(字符串)。

例如:

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 库(或其他解决方案)来解决此问题的任何方式?

非常感谢

【问题讨论】:

  • 这是题外话,因为您正在请求场外资源。此外,始终验证电话号码格式的理由可能有限。如果用户不想提供真实的电话号码,他们只会编一个。
  • 您问题的第一部分很容易证明不正确 - 大多数国家/地区使用 3 位拨号代码,有些使用 4、5 甚至 6:en.wikipedia.org/wiki/List_of_country_calling_codes
  • 他们的 github 页面作为演示链接到该网站 libphonenumber.appspot.com 并且他们的演示说使用“ISO 3166-1 两个字母的国家代码”并在此处链接:iso.org/iso/english_country_names_and_code_elements。所以也许可以尝试使用那些 2 个字符的字母代码而不是 1-3 位数字代码。例如,尝试在美国使用 US 而不是 840

标签: c# libphonenumber


【解决方案1】:

只要号码以 + 开头,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; 
}

【讨论】:

【解决方案2】:

你可以使用这个包的日期https://www.npmjs.com/package/dialcodes

【讨论】:

    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 2021-11-23
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    相关资源
    最近更新 更多