Table of Contents

Class PhoneNumberUtil

Namespace
PhoneNumbers
Assembly
PhoneNumbers.dll

Utility for international phone numbers. Functionality includes formatting, parsing and validation.

If you use this library, and want to be notified about important changes, please sign up to our mailing list: http://groups.google.com/group/libphonenumber-discuss/about

NOTE: A lot of methods in this class require Region Code strings.These must be provided using ISO 3166-1 two-letter country-code format.These should be in upper-case. The list of the codes can be found here: http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm

public sealed class PhoneNumberUtil
Inheritance
PhoneNumberUtil
Inherited Members

Fields

REGION_CODE_FOR_NON_GEO_ENTITY

public const string REGION_CODE_FOR_NON_GEO_ENTITY = "001"

Field Value

string

Methods

CanBeInternationallyDialled(PhoneNumber)

Returns true if the number can be dialled from outside the region, or unknown. If the number can only be dialled from within the region, returns false. Does not check the number is a valid number. TODO: Make this method public when we have enough metadata to make it worthwhile.

public bool CanBeInternationallyDialled(PhoneNumber number)

Parameters

number PhoneNumber

the phone-number for which we want to know whether it is only diallable from outside the region

Returns

bool

ConvertAlphaCharactersInNumber(string?)

Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting.

public static string ConvertAlphaCharactersInNumber(string? number)

Parameters

number string

Returns

string

CreateInstance(Stream)

Create a new PhoneNumberUtil instance to carry out international phone number formatting, parsing, or validation. The instance is loaded with all metadata by using the metadataLoader specified.

This method should only be used in the rare case in which you want to manage your own metadata loading. Calling this method multiple times is very expensive, as each time a new instance is created from scratch. When in doubt, use GetInstance().

public static PhoneNumberUtil CreateInstance(Stream metadataStream)

Parameters

metadataStream Stream

Stream of new metadata

Returns

PhoneNumberUtil

a PhoneNumberUtil instance

ExtractPossibleNumber(string)

Attempts to extract a possible number from the string passed in. This currently strips all leading characters that cannot be used to start a phone number. Characters that can be used to start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters are found in the number passed in, an empty string is returned. This function also attempts to strip off any alternative extensions or endings if two or more are present, such as in the case of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first number is parsed correctly.

public static string ExtractPossibleNumber(string number)

Parameters

number string

The string that might contain a phone number.

Returns

string

The number, stripped of any non-phone-number prefix (such as "Tel:") or an empty string if no character used to start phone numbers (such as + or any digit) is found in the number.

FindNumbers(string, string)

Returns an iterable over all PhoneNumberMatch PhoneNumberMatches in text. This is a shortcut for FindNumbers(string, string, Leniency, long) with Leniency.VALID and long.MaxValue.

public IEnumerable<PhoneNumberMatch> FindNumbers(string text, string defaultRegion)

Parameters

text string

The text to search for phone numbers, null for no text.

defaultRegion string

Region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. May be null if only international numbers are expected.

Returns

IEnumerable<PhoneNumberMatch>

FindNumbers(string, string, Leniency, long)

Returns an iterable over all PhoneNumberMatch PhoneNumberMatches in text.

public IEnumerable<PhoneNumberMatch> FindNumbers(string text, string defaultRegion, PhoneNumberUtil.Leniency leniency, long maxTries)

Parameters

text string

The text to search for phone numbers, null for no text.

defaultRegion string

Region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. May be null if only international numbers are expected.

leniency PhoneNumberUtil.Leniency

The leniency to use when evaluating candidate phone numbers.

maxTries long

The maximum number of invalid numbers to try before giving up on the text. This is to cover degenerate cases where the text has a lot of false positives in it. Must be >= 0.

Returns

IEnumerable<PhoneNumberMatch>

Format(PhoneNumber, PhoneNumberFormat)

Formats a phone number in the specified format using default rules. Note that this does not promise to produce a phone number that the user can dial from where they are - although we do format in either 'national' or 'international' format depending on what the client asks for, we do not currently support a more abbreviated format, such as for users in the same "area" who could potentially dial the number without area code. Note that if the phone number has a country calling code of 0 or an otherwise invalid country calling code, we cannot work out which formatting rules to apply so we return the national significant number with no formatting applied.

public string Format(PhoneNumber number, PhoneNumberFormat numberFormat)

Parameters

number PhoneNumber

The phone number to be formatted.

numberFormat PhoneNumberFormat

The format the phone number should be formatted into.

Returns

string

The formatted phone number.

Format(PhoneNumber, PhoneNumberFormat, StringBuilder)

Same as Format(PhoneNumber, PhoneNumberFormat), but accepts a mutable StringBuilder as a parameter to decrease object creation when invoked many times.

public void Format(PhoneNumber number, PhoneNumberFormat numberFormat, StringBuilder formattedNumber)

Parameters

number PhoneNumber
numberFormat PhoneNumberFormat
formattedNumber StringBuilder

FormatByPattern(PhoneNumber, PhoneNumberFormat, List<NumberFormat>)

Formats a phone number in the specified format using client-defined formatting rules. Note that if the phone number has a country calling code of zero or an otherwise invalid country calling code, we cannot work out things like whether there should be a national prefix applied, or how to format extensions, so we return the national significant number with no formatting applied.

public string FormatByPattern(PhoneNumber number, PhoneNumberFormat numberFormat, List<NumberFormat> userDefinedFormats)

Parameters

number PhoneNumber

The phone number to be formatted.

numberFormat PhoneNumberFormat

The format the phone number should be formatted into.

userDefinedFormats List<NumberFormat>

Formatting rules specified by clients.

Returns

string

The formatted phone number.

FormatInOriginalFormat(PhoneNumber, string)

Formats a phone number using the original phone number format (e.g. INTERNATIONAL or NATIONAL) that the number is parsed from, provided that the number has been parsed with ParseAndKeepRawInput(string, string). Otherwise the number will be formatted in NATIONAL format.The original format is embedded in the country_code_source field of the PhoneNumber object passed in, which is only set when parsing keeps the raw input. When we don't have a formatting pattern for the number, the method falls back to returning the raw input.

Note this method guarantees no digit will be inserted, removed or modified as a result of formatting.

public string FormatInOriginalFormat(PhoneNumber number, string regionCallingFrom)

Parameters

number PhoneNumber

The phone number that needs to be formatted in its original number format.

regionCallingFrom string

The region whose IDD needs to be prefixed if the original number has one.

Returns

string

The formatted phone number in its original number format.

FormatNationalNumberWithCarrierCode(PhoneNumber, string)

Formats a phone number in national format for dialing using the carrier as specified in the carrierCode. The carrierCode will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If carrierCode contains an empty string, returns the number in national format without any carrier code.

public string FormatNationalNumberWithCarrierCode(PhoneNumber number, string carrierCode)

Parameters

number PhoneNumber

The phone number to be formatted.

carrierCode string

The carrier selection code to be used.

Returns

string

The formatted phone number in national format for dialing using the carrier as specified in the carrierCode.

FormatNationalNumberWithPreferredCarrierCode(PhoneNumber, string)

Formats a phone number in national format for dialing using the carrier as specified in the preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing, use the fallbackCarrierCode passed in instead. If there is no preferredDomesticCarrierCode, and the fallbackCarrierCode contains an empty string, return the number in national format without any carrier code.

Use FormatNationalNumberWithCarrierCode(PhoneNumber, string) instead if the carrier code passed in should take precedence over the number's preferredDomesticCarrierCode when formatting.

public string FormatNationalNumberWithPreferredCarrierCode(PhoneNumber number, string fallbackCarrierCode)

Parameters

number PhoneNumber

The phone number to be formatted.

fallbackCarrierCode string

The carrier selection code to be used, if none is found in the phone number itself.

Returns

string

The formatted phone number in national format for dialing using the number's preferredDomesticCarrierCode, or the fallbackCarrierCode passed in if none is found.

FormatNumberForMobileDialing(PhoneNumber, string, bool)

Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region.If the number cannot be reached from the region(e.g.some countries block toll-free numbers from being called outside of the country), the method returns an empty string.

public string FormatNumberForMobileDialing(PhoneNumber number, string regionCallingFrom, bool withFormatting)

Parameters

number PhoneNumber

The phone number to be formatted.

regionCallingFrom string

The region where the call is being placed.

withFormatting bool

Whether the number should be returned with formatting symbols, such as spaces and dashes.

Returns

string

The formatted phone number.

FormatOutOfCountryCallingNumber(PhoneNumber, string)

Formats a phone number for out-of-country dialing purposes.If no regionCallingFrom is supplied, we format the number in its INTERNATIONAL format.If the country calling code is the same as that of the region where the number is from, then NATIONAL formatting will be applied.

If the number itself has a country calling code of zero or an otherwise invalid country calling code, then we return the number with no formatting applied.

Note this function takes care of the case for calling inside of NANPA and between Russia and Kazakhstan (who share the same country calling code). In those cases, no international prefix is used.For regions which have multiple international prefixes, the number in its INTERNATIONAL format will be returned instead.

public string FormatOutOfCountryCallingNumber(PhoneNumber number, string regionCallingFrom)

Parameters

number PhoneNumber

The phone number to be formatted.

regionCallingFrom string

The region where the call is being placed.

Returns

string

The formatted phone number.

FormatOutOfCountryKeepingAlphaChars(PhoneNumber, string)

Formats a phone number for out-of-country dialing purposes. Note that in this version, if the number was entered originally using alpha characters and this version of the number is stored in raw_input, this representation of the number will be used rather than the digit representation. Grouping information, as specified by characters such as "-" and " ", will be retained.

Caveats:

  • This will not produce good results if the country calling code is both present in the raw input _and_ is the start of the national number. This is not a problem in the regions which typically use alpha numbers.
  • This will also not produce good results if the raw input has any grouping information within the first three digits of the national number, and if the function needs to strip preceding digits/words in the raw input before these digits. Normally people group the first three digits together so this is not a huge problem - and will be fixed if it proves to be so.
public string FormatOutOfCountryKeepingAlphaChars(PhoneNumber number, string regionCallingFrom)

Parameters

number PhoneNumber

the phone number that needs to be formatted

regionCallingFrom string

the region where the call is being placed

Returns

string

the formatted phone number

GetAsYouTypeFormatter(string)

Gets an AsYouTypeFormatter for the specific region.

public AsYouTypeFormatter GetAsYouTypeFormatter(string regionCode)

Parameters

regionCode string

Region where the phone number is being entered.

Returns

AsYouTypeFormatter

An AsYouTypeFormatter object, which can be used to format phone numbers in the specific region "as you type".

GetCountryCodeForRegion(string)

Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand.

public int GetCountryCodeForRegion(string regionCode)

Parameters

regionCode string

Region that we want to get the country calling code for.

Returns

int

The country calling code for the region denoted by regionCode.

GetCountryMobileToken(int)

Returns the mobile token for the provided country calling code if it has one, otherwise returns an empty string. A mobile token is a number inserted before the area code when dialing a mobile number from that country from abroad.

public static string GetCountryMobileToken(int countryCallingCode)

Parameters

countryCallingCode int

The country calling code for which we want the mobile token.

Returns

string

The mobile token, as a string, for the given country calling code.

GetExampleNumber(string)

Gets a valid number for the specified region.

public PhoneNumber GetExampleNumber(string regionCode)

Parameters

regionCode string

Region for which an example number is needed.

Returns

PhoneNumber

A valid fixed-line number for the specified region.Returns null when the metadata does not contain such information, or the region 001 is passed in. For 001 (representing non - geographical numbers), call GetExampleNumberForNonGeoEntity(int) instead.

GetExampleNumberForNonGeoEntity(int)

Gets a valid number for the specified country calling code for a non-geographical entity.

public PhoneNumber GetExampleNumberForNonGeoEntity(int countryCallingCode)

Parameters

countryCallingCode int

The country calling code for a non-geographical entity

Returns

PhoneNumber

A valid number for the non-geographical entity. Returns null when the metadata does not contain such information, or the country calling code passed in does not belong to a non-geographical entity.

GetExampleNumberForType(string, PhoneNumberType)

Gets a valid number for the specified region and number type.

public PhoneNumber GetExampleNumberForType(string regionCode, PhoneNumberType type)

Parameters

regionCode string

Region for which an example number is needed.

type PhoneNumberType

The type of number that is needed.

Returns

PhoneNumber

A valid number for the specified region and type. Returns null when the metadata does not contain such information or if an invalid region or region 001 was entered. For 001 (representing non-geographical numbers), call GetExampleNumberForNonGeoEntity(int) instead.

GetInstance()

Gets a PhoneNumberUtil instance to carry out international phone number formatting, parsing, or validation. The instance is loaded with phone number metadata for a number of most commonly used regions.

The PhoneNumberUtil is implemented as a singleton. Therefore, calling getInstance multiple times will only result in one instance being created.

public static PhoneNumberUtil GetInstance()

Returns

PhoneNumberUtil

A PhoneNumberUtil instance.

GetInstance(string, Dictionary<int, List<string>>)

Gets a PhoneNumberUtil instance to carry out international phone number formatting, parsing, or validation. The instance is loaded with all phone number metadata. The PhoneNumberUtil is implemented as a singleton. Therefore, calling getInstance multiple times will only result in one instance being created.

public static PhoneNumberUtil GetInstance(string baseFileLocation, Dictionary<int, List<string>> countryCallingCodeToRegionCodeMap = null)

Parameters

baseFileLocation string
countryCallingCodeToRegionCodeMap Dictionary<int, List<string>>

Returns

PhoneNumberUtil

a PhoneNumberUtil instance

GetLengthOfGeographicalAreaCode(PhoneNumber)

Gets the length of the geographical area code from the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber number. It works in such a way that the resultant subscriber number should be diallable, at least on some devices. An example of how this could be used:

var phoneUtil = PhoneNumberUtil.getInstance();
var number = phoneUtil.parse("16502530000", "US");
var nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
string areaCode;
string subscriberNumber;

var areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
if (areaCodeLength > 0)
{
  areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
  subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
}
else {
  areaCode = "";
  subscriberNumber = nationalSignificantNumber;
}

N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against using it for most purposes, but recommends using the more general NationalNumber instead. Read the following carefully before deciding to use this method:

  • geographical area codes change over time, and this method honors those changes; therefore, it doesn't guarantee the stability of the result it produces.
  • subscriber numbers may not be diallable from all devices (notably mobile devices, which typically requires the full NationalNumber to be dialled in most regions).
  • most non-geographical numbers have no area codes, including numbers from non-geographical entities
  • some geographical numbers have no area codes.
public int GetLengthOfGeographicalAreaCode(PhoneNumber number)

Parameters

number PhoneNumber

the PhoneNumber object for which clients want to know the length of the area code

Returns

int

the length of area code of the PhoneNumber object passed in

GetLengthOfNationalDestinationCode(PhoneNumber)

Gets the length of the national destination code (NDC) from the PhoneNumber object passed in, so that clients could use it to split a national significant number into NDC and subscriber number. The NDC of a phone number is normally the first group of digit(s) right after the country calling code when the number is formatted in the international format, if there is a subscriber number part that follows.

N.B.: similar to an area code, not all numbers have an NDC!

An example of how this could be used:

var phoneUtil = PhoneNumberUtil.getInstance();
var number = phoneUtil.parse("18002530000", "US");
var nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
string nationalDestinationCode;
string subscriberNumber;

var nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
if (nationalDestinationCodeLength > 0)
{
  nationalDestinationCode = nationalSignificantNumber.substring(0,
      nationalDestinationCodeLength);
  subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
}
else
{
  nationalDestinationCode = "";
  subscriberNumber = nationalSignificantNumber;
}

Refer to the unit tests to see the difference between this function and GetLengthOfGeographicalAreaCode(PhoneNumber).

public int GetLengthOfNationalDestinationCode(PhoneNumber number)

Parameters

number PhoneNumber

the PhoneNumber object for which clients want to know the length of the NDC.

Returns

int

the length of NDC of the PhoneNumber object passed in, which could be zero

GetMetadataForNonGeographicalRegion(int)

public PhoneMetadata GetMetadataForNonGeographicalRegion(int countryCallingCode)

Parameters

countryCallingCode int

Returns

PhoneMetadata

GetMetadataForRegion(string)

public PhoneMetadata GetMetadataForRegion(string regionCode)

Parameters

regionCode string

Returns

PhoneMetadata

GetNationalSignificantNumber(PhoneNumber)

Gets the national significant number of the a phone number. Note a national significant number doesn't contain a national prefix or any formatting.

public string GetNationalSignificantNumber(PhoneNumber number)

Parameters

number PhoneNumber

The PhoneNumber object for which the national significant number is needed.

Returns

string

The national significant number of the PhoneNumber object passed in.

GetNddPrefixForRegion(string, bool)

Returns the national dialling prefix for a specific region. For example, this would be 1 for the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~" (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is present, we return null.

Warning: Do not use this method for do-your-own formatting - for some regions, the national dialling prefix is used only for certain types of numbers. Use the library's formatting functions to prefix the national prefix when required.

public string GetNddPrefixForRegion(string regionCode, bool stripNonDigits)

Parameters

regionCode string

The region that we want to get the dialling prefix for.

stripNonDigits bool

True to strip non-digits from the national dialling prefix.

Returns

string

The dialling prefix for the region denoted by regionCode.

GetNumberType(PhoneNumber)

Gets the type of a phone number.

public PhoneNumberType GetNumberType(PhoneNumber number)

Parameters

number PhoneNumber

The phone number that we want to know the type.

Returns

PhoneNumberType

The type of the phone number.

GetRegionCodeForCountryCode(int)

Returns the region code that matches the specific country calling code. In the case of no region code being found, ZZ will be returned. In the case of multiple regions, the one designated in the metadata as the "main" region for this calling code will be returned.

public string GetRegionCodeForCountryCode(int countryCallingCode)

Parameters

countryCallingCode int

Returns

string

GetRegionCodeForNumber(PhoneNumber)

Returns the region where a phone number is from. This could be used for geocoding at the region level.

public string GetRegionCodeForNumber(PhoneNumber number)

Parameters

number PhoneNumber

The phone number whose origin we want to know.

Returns

string

The region where the phone number is from, or null if no region matches this calling code.

GetRegionCodesForCountryCode(int)

Returns the region codes that match the specific country calling code. For non-geographical country calling codes, the region code 001 is returned. Also, in the case of no region code being found, an empty list is returned.

public IReadOnlyList<string> GetRegionCodesForCountryCode(int countryCallingCode)

Parameters

countryCallingCode int

The country calling code for which region codes are wanted.

Returns

IReadOnlyList<string>

The region codes that match the given country calling code.

GetSupportedCallingCodes()

Returns all country calling codes the library has metadata for, covering both non-geographical entities (global network calling codes) and those used for geographical entities. This could be used to populate a drop-down box of country calling codes for a phone-number widget, for instance.

public HashSet<int> GetSupportedCallingCodes()

Returns

HashSet<int>

An unordered set of the country calling codes for every geographical and non-geographical entity the library supports.

GetSupportedGlobalNetworkCallingCodes()

Returns all global network calling codes the library has metadata for.

public Dictionary<int, PhoneMetadata>.KeyCollection GetSupportedGlobalNetworkCallingCodes()

Returns

Dictionary<int, PhoneMetadata>.KeyCollection

An unordered set of the country calling codes for every non-geographical entity the library supports (e.g. 800, 808, 870 for international toll-free / shared-cost / etc.).

Remarks

The semantics match Java's getSupportedGlobalNetworkCallingCodes(): only calling codes that map exclusively to non-geographical entities. The pre-binary-metadata implementation incidentally returned every loaded calling code (geographical too) because it leaked an internal dictionary populated by the eager XML loader; that was a bug — the docstring always promised "non-geographical entity" only.

GetSupportedRegions()

Returns all regions the library has metadata for.

public HashSet<string> GetSupportedRegions()

Returns

HashSet<string>

An unordered set of the two-letter region codes for every geographical region the library supports.

GetSupportedTypesForNonGeoEntity(int)

Returns the types for a country-code belonging to a non-geographical entity which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers for this non-geographical entity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN.

No types will be returned for country calling codes that do not map to a known non-geographical entity.

public HashSet<PhoneNumberType> GetSupportedTypesForNonGeoEntity(int countryCallingCode)

Parameters

countryCallingCode int

Returns

HashSet<PhoneNumberType>

GetSupportedTypesForRegion(string)

Returns the types for a given region which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers in this region could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN.

No types will be returned for invalid or unknown region codes.

public HashSet<PhoneNumberType> GetSupportedTypesForRegion(string regionCode)

Parameters

regionCode string

Returns

HashSet<PhoneNumberType>

IsAlphaNumber(string)

Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity number will start with at least 3 digits and will have three or more alpha characters. This does not do region-specific checks - to work out if this number is actually valid for a region, it should be parsed and methods such as IsPossibleNumberWithReason(PhoneNumber) and IsValidNumber(PhoneNumber) should be used.

public bool IsAlphaNumber(string number)

Parameters

number string

The number that needs to be checked.

Returns

bool

True if the number is a valid vanity number.

IsMobileNumberPortableRegion(string)

Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability.

public bool IsMobileNumberPortableRegion(string regionCode)

Parameters

regionCode string

The region for which we want to know whether it supports mobile number portability or not.

Returns

bool

True if the region supports mobile number portability, false otherwise.

IsNANPACountry(string)

Checks if this is a region under the North American Numbering Plan Administration (NANPA).

public bool IsNANPACountry(string regionCode)

Parameters

regionCode string

Returns

bool

True if regionCode is one of the regions under NANPA.

IsNumberGeographical(PhoneNumber)

Tests whether a phone number has a geographical association. It checks if the number is associated with a certain region in the country to which it belongs. Note that this doesn't verify if the number is actually in use.

public bool IsNumberGeographical(PhoneNumber phoneNumber)

Parameters

phoneNumber PhoneNumber

Returns

bool

IsNumberGeographical(PhoneNumberType, int)

Overload of isNumberGeographical(PhoneNumber), since calculating the phone number type is expensive; if we have already done this, we don't want to do it again.

public bool IsNumberGeographical(PhoneNumberType phoneNumberType, int countryCallingCode)

Parameters

phoneNumberType PhoneNumberType
countryCallingCode int

Returns

bool

IsNumberMatch(PhoneNumber, PhoneNumber)

Takes two phone numbers and compares them for equality.

Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same.

Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not.

Returns NO_MATCH otherwise. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.

public PhoneNumberUtil.MatchType IsNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn)

Parameters

firstNumberIn PhoneNumber

First number to compare.

secondNumberIn PhoneNumber

Second number to compare.

Returns

PhoneNumberUtil.MatchType

NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality of the two numbers, described in the method definition.

IsNumberMatch(PhoneNumber, string)

Takes two phone numbers and compares them for equality. This is a convenience wrapper for IsNumberMatch(PhoneNumber, PhoneNumber). No default region is known.

public PhoneNumberUtil.MatchType IsNumberMatch(PhoneNumber firstNumber, string secondNumber)

Parameters

firstNumber PhoneNumber

First number to compare in proto buffer format.

secondNumber string

Second number to compare. Can contain formatting, and can have country calling code specified with + at the start.

Returns

PhoneNumberUtil.MatchType

NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See IsNumberMatch(PhoneNumber, PhoneNumber) for more details.

IsNumberMatch(string, string)

Takes two phone numbers as strings and compares them for equality. This is a convenience wrapper for IsNumberMatch(PhoneNumber, PhoneNumber). No default region is known.

public PhoneNumberUtil.MatchType IsNumberMatch(string firstNumber, string secondNumber)

Parameters

firstNumber string

First number to compare. Can contain formatting, and can have country calling code specified with + at the start.

secondNumber string

Second number to compare. Can contain formatting, and can have country calling code specified with + at the start.

Returns

PhoneNumberUtil.MatchType

NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See IsNumberMatch(PhoneNumber, PhoneNumber) for more details.

IsPossibleNumber(PhoneNumber)

Convenience wrapper around IsPossibleNumberWithReason(PhoneNumber). Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it.

public bool IsPossibleNumber(PhoneNumber number)

Parameters

number PhoneNumber

The number that needs to be checked.

Returns

bool

True if the number is possible.

IsPossibleNumber(string, string)

Check whether a phone number is a possible number given a number in the form of a string, and the region where the number could be dialed from. It provides a more lenient check than IsValidNumber(PhoneNumber). See IsPossibleNumber(PhoneNumber) for details.

This method first parses the number, then invokes IsPossibleNumber(PhoneNumber) with the resultant PhoneNumber object.

public bool IsPossibleNumber(string number, string regionDialingFrom)

Parameters

number string

The number that needs to be checked, in the form of a string.

regionDialingFrom string

The region that we are expecting the number to be dialed from. Note this is different from the region where the number belongs. For example, the number +1 650 253 0000 is a number that belongs to US. When written in this form, it can be dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any region which uses an international dialling prefix of 00. When it is written as 650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it can only be dialed from within a smaller area in the US (Mountain View, CA, to be more specific).

Returns

bool

True if the number is possible.

IsPossibleNumberForType(PhoneNumber, PhoneNumberType)

Convenience wrapper around IsPossibleNumberForTypeWithReason(PhoneNumber, PhoneNumberType). Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it.

public bool IsPossibleNumberForType(PhoneNumber number, PhoneNumberType type)

Parameters

number PhoneNumber

the number that needs to be checked

type PhoneNumberType

the type we are interested in

Returns

bool

if the number is possible for this particular type

IsPossibleNumberForTypeWithReason(PhoneNumber, PhoneNumberType)

Check whether a phone number is a possible number of a particular type. For types that don't exist in a particular region, this will return a result that isn't so useful; it is recommended that you use GetSupportedTypesForRegion(string) or GetSupportedTypesForNonGeoEntity(int) respectively before calling this method to determine whether you should call it for this number at all.

This provides a more lenient check than IsValidNumber(PhoneNumber) in the following sense:

  1. It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number.
  2. For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because isValidNumber validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version.
public PhoneNumberUtil.ValidationResult IsPossibleNumberForTypeWithReason(PhoneNumber number, PhoneNumberType type)

Parameters

number PhoneNumber

the number that needs to be checked

type PhoneNumberType

the type we are interested in

Returns

PhoneNumberUtil.ValidationResult

A ValidationResult object which indicates whether the number is possible

IsPossibleNumberWithReason(PhoneNumber)

Check whether a phone number is a possible number. It provides a more lenient check than IsValidNumber(PhoneNumber) in the following sense:

  1. It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number.
  2. It doesn't attempt to figure out the type of the number, but uses general rules which applies to all types of phone numbers in a region. Therefore, it is much faster than isValidNumber.
  3. For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because isValidNumber validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version.
public PhoneNumberUtil.ValidationResult IsPossibleNumberWithReason(PhoneNumber number)

Parameters

number PhoneNumber

the number that needs to be checked

Returns

PhoneNumberUtil.ValidationResult

a ValidationResult object which indicates whether the number is possible

IsValidNumber(PhoneNumber)

Tests whether a phone number matches a valid pattern. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself.

public bool IsValidNumber(PhoneNumber number)

Parameters

number PhoneNumber

The phone number that we want to validate.

Returns

bool

A bool that indicates whether the number is of a valid pattern.

IsValidNumberForRegion(PhoneNumber, string)

Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number.

public bool IsValidNumberForRegion(PhoneNumber number, string regionCode)

Parameters

number PhoneNumber

The phone number that we want to validate.

regionCode string

The region that we want to validate the phone number for.

Returns

bool

A bool that indicates whether the number is of a valid pattern.

IsViablePhoneNumber(string)

Checks to see if the string of characters could possibly be a phone number at all. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-number symbols have been removed, such as by the method extractPossibleNumber.

public static bool IsViablePhoneNumber(string number)

Parameters

number string

String to be checked for viability as a phone number.

Returns

bool

True if the number could be a phone number of some sort, otherwise false.

MaybeExtractCountryCode(string, PhoneMetadata, StringBuilder, bool, Builder)

Tries to extract a country calling code from a number. This method will return zero if no country calling code is considered to be present. Country calling codes are extracted in the following ways:

  • by stripping the international dialing prefix of the region the person is dialing from, if this is present in the number, and looking at the next digits
  • by stripping the '+' sign if present and then looking at the next digits
  • by comparing the start of the number and the country calling code of the default region. If the number is not considered possible for the numbering plan of the default region initially, but starts with the country calling code of this region, validation will be reattempted after stripping this country calling code. If this number is considered a possible number, then the first digits will be considered the country calling code and removed as such.

It will throw a NumberParseException if the number starts with a '+' but the country calling code supplied after this does not match that of any known region.

public int MaybeExtractCountryCode(string number, PhoneMetadata defaultRegionMetadata, StringBuilder nationalNumber, bool keepRawInput, PhoneNumber.Builder phoneNumber)

Parameters

number string

non-normalized telephone number that we wish to extract a country calling code from - may begin with '+'

defaultRegionMetadata PhoneMetadata

metadata about the region this number may be from

nationalNumber StringBuilder

a string buffer to store the national significant number in, in the case that a country calling code was extracted. The number is appended to any existing contents. If no country calling code was extracted, this will be left unchanged.

keepRawInput bool

true if the country_code_source and preferred_carrier_code fields of phoneNumber should be populated.

phoneNumber PhoneNumber.Builder

the PhoneNumber object where the country_code and country_code_source need to be populated. Note the country_code is always populated, whereas country_code_source is only populated when keepCountryCodeSource is true.

Returns

int

the country calling code extracted or 0 if none could be extracted

MaybeStripInternationalPrefixAndNormalize(StringBuilder, string)

Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes the resulting number, and indicates if an international prefix was present.

public PhoneNumber.Types.CountryCodeSource MaybeStripInternationalPrefixAndNormalize(StringBuilder number, string possibleIddPrefix)

Parameters

number StringBuilder

The non-normalized telephone number that we wish to strip any international dialing prefix from.

possibleIddPrefix string

The international direct dialing prefix from the region we think this number may be dialed in.

Returns

PhoneNumber.Types.CountryCodeSource

The corresponding CountryCodeSource if an international dialing prefix could be removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did not seem to be in international format.

MaybeStripNationalPrefixAndCarrierCode(StringBuilder, PhoneMetadata, StringBuilder)

Strips any national prefix (such as 0, 1) present in the number provided.

public bool MaybeStripNationalPrefixAndCarrierCode(StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode)

Parameters

number StringBuilder

The normalized telephone number that we wish to strip any national dialing prefix from.

metadata PhoneMetadata

The metadata for the region that we think this number is from.

carrierCode StringBuilder

A place to insert the carrier code if one is extracted.

Returns

bool

True if a national prefix or carrier code (or both) could be extracted.

Normalize(string?)

Normalizes a string of characters representing a phone number. This performs the following conversions: Punctuation is stripped. For ALPHA/VANITY numbers: Letters are converted to their numeric representation on a telephone keypad. The keypad used here is the one defined in ITU Recommendation E.161. This is only done if there are 3 or more letters in the number, to lessen the risk that such letters are typos. For other numbers: Wide-ascii digits are converted to normal ASCII (European) digits. Arabic-Indic numerals are converted to European numerals. Spurious alpha characters are stripped. Arabic-Indic numerals are converted to European numerals.

public static string Normalize(string? number)

Parameters

number string

A string of characters representing a phone number.

Returns

string

The normalized string version of the phone number.

NormalizeDiallableCharsOnly(string?)

Normalizes a string of characters representing a phone number. This strips all characters which are not diallable on a mobile phone keypad (including all non-ASCII digits).

public static string NormalizeDiallableCharsOnly(string? number)

Parameters

number string

a string of characters representing a phone number

Returns

string

the normalized string version of the phone number

NormalizeDigitsOnly(string?)

Normalizes a string of characters representing a phone number. This converts wide-ascii and arabic-indic numerals to European numerals, and strips punctuation and alpha characters.

public static string NormalizeDigitsOnly(string? number)

Parameters

number string

A string of characters representing a phone number.

Returns

string

The normalized string version of the phone number.

Parse(string, string)

Parses a string and returns it in proto buffer format. This method will throw a NumberParseException if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with IsValidNumber(PhoneNumber).

public PhoneNumber Parse(string numberToParse, string defaultRegion)

Parameters

numberToParse string

Number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966 format.

defaultRegion string

Region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then "ZZ" or null can be supplied.

Returns

PhoneNumber

A phone number proto buffer filled with the parsed number

Exceptions

NumberParseException

If the string is not considered to be a viable phone number or if no default region was supplied and the number is not in international format (does not start with +).

Parse(string, string, Builder)

Same as Parse(string, string), but accepts mutable PhoneNumber as a parameter to decrease object creation when invoked many times.

public void Parse(string numberToParse, string defaultRegion, PhoneNumber.Builder phoneNumber)

Parameters

numberToParse string
defaultRegion string
phoneNumber PhoneNumber.Builder

ParseAndKeepRawInput(string, string)

Parses a string and returns it in proto buffer format. This method differs from Parse(string, string) in that it always populates the raw_input field of the protocol buffer with numberToParse as well as the country_code_source field.

public PhoneNumber ParseAndKeepRawInput(string numberToParse, string defaultRegion)

Parameters

numberToParse string

Number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension.

defaultRegion string

Region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country calling code for the number in this case would be stored as that of the default region supplied.

Returns

PhoneNumber

A phone number proto buffer filled with the parsed number.

Exceptions

NumberParseException

If the string is not considered to be a viable phone number or if no default region was supplied.

ParseAndKeepRawInput(string, string, Builder)

Same as ParseAndKeepRawInput(string, string), but accepts a mutable PhoneNumber as a parameter to decrease object creation when invoked many times.

public void ParseAndKeepRawInput(string numberToParse, string defaultRegion, PhoneNumber.Builder phoneNumber)

Parameters

numberToParse string
defaultRegion string
phoneNumber PhoneNumber.Builder

TruncateTooLongNumber(Builder)

Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified.

public bool TruncateTooLongNumber(PhoneNumber.Builder number)

Parameters

number PhoneNumber.Builder

A PhoneNumber object which contains a number that is too long to be valid.

Returns

bool

True if a valid phone number can be successfully extracted.

Verify(Leniency, PhoneNumber, string, PhoneNumberUtil, PhoneNumberMatcher)

public bool Verify(PhoneNumberUtil.Leniency leniency, PhoneNumber number, string candidate, PhoneNumberUtil util, PhoneNumberMatcher matcher)

Parameters

leniency PhoneNumberUtil.Leniency
number PhoneNumber
candidate string
util PhoneNumberUtil
matcher PhoneNumberMatcher

Returns

bool