public Format ( |
||
number | ||
numberFormat | PhoneNumberFormat | |
return | String |
/// <summary> /// Formats a phone number to display formats. /// If it belongs to the region, the national format is returned, /// else the international format is returned. /// </summary> /// <param name="phoneNumber">A phone number which belongs to the region, or a phone number in international format.</param> /// <param name="region">The region to use for formatting.</param> /// <returns>Returns the formatted string, if the phoneNumber is valid, else the original phoneNumber</returns> public string Format(string phoneNumber, string region) { if (string.IsNullOrWhiteSpace(phoneNumber)) { return(phoneNumber); } lock (Locker) { try { var number = _fnu.Parse(phoneNumber, region); if (!_fnu.IsValidNumber(number)) { return(phoneNumber); } return(_fnu.Format(number, _fnu.GetRegionCodeForNumber(number).Equals(region.ToUpperInvariant()) ? PhoneNumbers.PhoneNumberFormat.NATIONAL : PhoneNumbers.PhoneNumberFormat.INTERNATIONAL)); } catch (Exception e) { _logger.LogDebug(e, "{@phoneNumber}", phoneNumber); return(phoneNumber); } } }
/// <summary> /// Try gets the phonenumber formatted in E164 if it was valid for the first country as specified in order of countries passed in /// </summary> /// <param name="phoneUtil">PhoneNumberUtil instance</param> /// <param name="numberString">The phonenumber to get </param> /// <param name="countryCodes">The countries to check for a valid phonenumber</param> /// <param name="formattedPhoneNumber">The phonenumber formatted in E164</param> /// <returns>True if successfully retrieves the formatted phonenumber; else false</returns> public static bool TryGetFormattedPhoneNumber(this PhoneNumbers.PhoneNumberUtil phoneUtil, string numberString, string[] countryCodes, out string formattedPhoneNumber) { formattedPhoneNumber = null; foreach (var countryCode in countryCodes) { var phoneNumber = phoneUtil.Parse(numberString, countryCode); if (phoneUtil.IsValidNumber(phoneNumber)) { formattedPhoneNumber = phoneUtil.Format(phoneNumber, PhoneNumberFormat.E164); return(true); } } return(false); }
/** * Helper method to get the national-number part of a number, formatted without any national * prefix, and return it as a set of digit blocks that would be formatted together. */ internal static String[] GetNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number) { // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits. String rfc3966Format = util.Format(number, PhoneNumberFormat.RFC3966); // We remove the extension part from the formatted string before splitting it into different // groups. int endIndex = rfc3966Format.IndexOf(';'); if (endIndex < 0) { endIndex = rfc3966Format.Length; } // The country-code will have a '-' following it. int startIndex = rfc3966Format.IndexOf('-') + 1; return rfc3966Format.Substring(startIndex, endIndex - startIndex).Split('-'); }