前言
Google libphonenumber 是 Java 的, ASP.NET Core 只是 port 过去而已.
以前在 angular2 学习笔记 ( translate, i18n 翻译 ) 有介绍过. 但后来就一直没怎么用过了.
参考
Github – Google libphonenumber
Github – libphonenumber-csharp
Stack Overflow – Listing all country codes of phone numbers
相关链接
Github – CountryCodes.json (JSON)
geonames.org (API)
Wikipedia – List of country calling codes
nuget 安装
dotnet add package libphonenumber-csharp
基本操作
Get Phone Number Information
var singaporeNumber = "+6590269356"; var phoneUtil = PhoneNumberUtil.GetInstance(); PhoneNumber number = phoneUtil.Parse(singaporeNumber, defaultRegion: ""); var regionCode = phoneUtil.GetRegionCodeForNumber(number); // SG var isValidNumber = phoneUtil.IsValidNumber(number); var internationalFormat = phoneUtil.Format(number, PhoneNumberFormat.INTERNATIONAL); //+65 9026 9356 var localFormat = phoneUtil.Format(number, PhoneNumberFormat.NATIONAL); // 9026 9356
当获取到一个用户输入的号码, 我们可以通过 PhoneNumberUtil 检查它是否 valid, 是属于什么国家, 还可以获取它的正规格式.
-RegionCode 指的是 Country String Code, 比如 Malaysia = MY, Singapore = SG
-CountryCode 指的是 Dial Code, 比如 Malaysia = 60, Singapore = 65
Get All Code List Information
var phoneUtil = PhoneNumberUtil.GetInstance(); List<int> countryCodes = phoneUtil.GetSupportedCallingCodes().ToList(); // e.g. 60, 65 foreach (var countryCode in countryCodes) { var regionCode = phoneUtil.GetRegionCodeForCountryCode(countryCode); // e.g. MY, SG try { var countryName = new Locale("", regionCode).GetDisplayCountry("en"); // e.g. Malaysia, Singapore } catch { // 247, 599, 211, 383, 800, 808, 870, 878, 881, 882, 883, 888, 979 // 上面这些 CountryCode/DialCode 的 RegionCode 对不上任何国家...我不知道为什么, 但 Wikipedia 也找不到这些 DialCode noCountryNames.Add(countryCode); } }
上面是拿 country code / dial code > 转去 region code > 获取 country name
先拿 region code > 转去 country code 也可以
var regionCodes = phoneUtil.GetSupportedRegions(); // e.g. MY, SG var countryCode = phoneUtil.GetCountryCodeForRegion("MY"); // 60