PhoneNumberUtil class
fileoverview
Utility for international phone numbers.
Functionality includes formatting, parsing and validation.
(based on the java implementation).
NOTE: A lot of methods in this class require Region Code strings. These must be provided using CLDR two-letter region-code format. These should be in upper-case. The list of the codes can be found here: http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
Constructors
- PhoneNumberUtil(MetadataMapLoader _metadataMapLoader)
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
-
regionToMetadataMap
→ Map<
String, PhoneMetadata> -
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
-
supportedGlobalNetworkCallingCodes
→ List<
int> -
Returns all global network calling codes the library has metadata for.
This returns the country calling codes for every
non-geographical entity the library supports.
no setter
-
supportedRegions
→ List<
String> -
Returns all regions the library has metadata for.
This returns the two-letter region codes for every geographical
region the library supports.
no setter
Methods
-
canBeInternationallyDialled(
PhoneNumber number) → bool - 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. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country).
-
chooseFormattingPatternForNumber(
List< NumberFormat> availableFormats, String nationalNumber) → NumberFormat? -
availableFormats
the available formats the phone number could be formatted into.nationalNumber
a string of characters representing a phone number. -
convertAlphaCharactersInNumber(
String number) → String - Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting. Also converts wide-ascii digits to normal ascii digits, and converts Arabic-Indic numerals to European numerals.
-
extractCountryCode(
StringBuffer fullNumber, StringBuffer nationalNumber) → int - Extracts country calling code from fullNumber, returns it and places the remaining number in nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified.
-
findNumbers(
String text, String defaultRegion, [Leniency leniency = Leniency.valid, Int64 maxTries = Int64.MAX_VALUE]) → Iterable< PhoneNumberMatch> -
Returns an iterable over all PhoneNumberMatch PhoneNumberMatches in
text
. -
format(
PhoneNumber number, PhoneNumberFormat numberFormat) → String - 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.
-
formatByPattern(
PhoneNumber number, PhoneNumberFormat numberFormat, List< NumberFormat> userDefinedFormats) → String - 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.
-
formatInOriginalFormat(
PhoneNumber number, String regionCallingFrom) → String -
Formats a phone number using the original phone number format that the number
is parsed from. The original format is embedded in the
countryCodeSource
field of the PhoneNumber object passed in. If such information is missing, the number will be formatted into thenational
format by default. When the number contains a leading zero and this is unexpected for this country, or we don't have a formatting pattern for the number, the method returns the raw input when it is available. -
formatNationalNumberWithCarrierCode(
PhoneNumber number, String carrierCode) → String - Formats a phone number in national format for dialing using the carrier as specified in the {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If {@code carrierCode} contains an empty string, returns the number in national format without any carrier code.
-
formatNationalNumberWithPreferredCarrierCode(
PhoneNumber number, String fallbackCarrierCode) → 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 thefallbackCarrierCode
passed in instead. If there is nopreferredDomesticCarrierCode
, and thefallbackCarrierCode
contains an empty string, return the number in national format without any carrier code. -
formatNsnUsingPattern(
String nationalNumber, NumberFormat formattingPattern, PhoneNumberFormat numberFormat, [String? optCarrierCode]) → String - Note that carrierCode is optional - if null or an empty string, no carrier code replacement will take place.
-
formatNumberForMobileDialing(
PhoneNumber number, String regionCallingFrom, bool withFormatting) → String - 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.
-
formatOutOfCountryCallingNumber(
PhoneNumber number, String regionCallingFrom) → 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, thennational
formatting will be applied. -
formatOutOfCountryKeepingAlphaChars(
PhoneNumber number, String regionCallingFrom) → String - Formats a phone number for out-of-country dialing purposes.
-
getAlternateFormatsMetadata(
int countryCode) → PhoneMetadata? -
getAsYouTypeFormatter(
String regionCode) → AsYouTypeFormatter - Gets an AsYouTypeFormatter for the specific region.
-
getCountryCodeForRegion(
String? regionCode) → int - Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand.
-
getExampleNumber(
String regionCode) → PhoneNumber? - Gets a valid number for the specified region.
-
getExampleNumberForNonGeoEntity(
int countryCallingCode) → PhoneNumber? - Gets a valid number for the specified country calling code for a non-geographical entity.
-
getExampleNumberForType(
{String? regionCode, required PhoneNumberType type}) → PhoneNumber? - Gets a valid number for the specified region and number type.
-
getInvalidExampleNumber(
String regionCode) → PhoneNumber? - Gets an invalid number for the specified region. This is useful for unit-testing purposes, where you want to test what will happen with an invalid number. Note that the number that is returned will always be able to be parsed and will have the correct country code. It may also be a valid short number/code for this region. Validity checking such numbers is handled with ShortNumberInfo.
-
getLengthOfGeographicalAreaCode(
PhoneNumber number) → int -
Gets the length of the geographical area code from the
nationalNumber
field of 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: -
getLengthOfNationalDestinationCode(
PhoneNumber number) → int - 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.
-
getMetadataForNonGeographicalRegion(
int countryCallingCode) → PhoneMetadata? -
getMetadataForRegion(
{String? regionCode, int? countryCode}) → PhoneMetadata? -
Returns the metadata for the given
regionCode
or null if the region code is invalid or unknown. -
getNationalSignificantNumber(
PhoneNumber number) → String - Gets the national significant number of a phone number. Note a national significant number doesn't contain a national prefix or any formatting.
-
getNddPrefixForRegion(
String? regionCode, bool stripNonDigits) → String? - 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.
-
getNumberType(
PhoneNumber number) → PhoneNumberType - Gets the type of a valid phone number.
-
getRegionCodeForCountryCode(
int countryCallingCode) → String - 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.
-
getRegionCodeForNumber(
PhoneNumber? number) → String? - Returns the region where a phone number is from. This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers).
-
getRegionCodesForCountryCode(
int countryCallingCode) → List< String> - Returns a list with 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.
-
getSupportedCallingCodes(
) → List< int> - 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.
-
getSupportedTypesForNonGeoEntity(
int countryCallingCode) → List< PhoneNumberType> -
Returns the types for a country-code belonging to a non-geographical entity
which the library has metadata for. Will not include
fixedLineOrMobile
(instead bothfixedLine
andfixedLineOrMobile
(if numbers for this non-geographical entity could be classified asfixedLineOrMobile
, bothfixedLine
andmobile
would be present) andunknown
. -
getSupportedTypesForRegion(
String? regionCode) → List< PhoneNumberType> -
Returns the types for a given region which the library has metadata for.
Will not include
fixedLineOrMobile
(if numbers for this non-geographical entity could be classified asfixedLineOrMobile
, bothfixedLine
andmobile
would be present) andunknown
. -
isAlphaNumber(
String number) → bool - 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 and isValidNumber should be used.
-
isMobileNumberPortableRegion(
String? regionCode) → bool - Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability.
-
isNANPACountry(
String? regionCode) → bool - Checks if this is a region under the North American Numbering Plan Administration (NANPA).
-
isNumberGeographical(
{PhoneNumber? phoneNumber, PhoneNumberType? phoneNumberType, int? countryCallingCode}) → bool - 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.
-
isNumberMatch(
Object firstNumberIn, Object secondNumberIn) → MatchType - Takes two phone numbers and compares them for equality.
-
isPossibleNumber(
PhoneNumber number) → bool - Convenience wrapper around isPossibleNumberWithReason. 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.
-
isPossibleNumberForType(
PhoneNumber number, PhoneNumberType type) → bool - Convenience wrapper around isPossibleNumberForTypeWithReason. 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.
-
isPossibleNumberForTypeWithReason(
PhoneNumber number, PhoneNumberType type) → ValidationResult - Check whether a phone number is a possible number. It provides a more lenient check than isValidNumber in the following sense:
-
isPossibleNumberString(
String number, String regionDialingFrom) → bool - 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. See isPossibleNumber for details.
-
isPossibleNumberWithReason(
PhoneNumber number) → ValidationResult - Check whether a phone number is a possible number. It provides a more lenient check than isValidNumber in the following sense:
-
isValidNumber(
PhoneNumber number) → bool - 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. It only verifies whether the parsed, canonicalised number is valid: not whether a particular series of digits entered by the user is diallable from the region provided when parsing. For example, the number +41 (0) 78 927 2696 can be parsed into a number with country code '41' and national significant number '789272696'. This is valid, while the original string is not diallable.
-
isValidNumberForRegion(
PhoneNumber number, String? regionCode) → bool - 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. Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region 'GB' (United Kingdom), since it has its own region code, 'IM', which may be undesirable.
-
isViablePhoneNumber(
String number) → bool -
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.
number
is the string to be checked for viability as a phone number. isViablePhoneNumber returns true if the number could be a phone number of some sort, otherwise false. -
matchesEntirely(
Pattern regex, String str) → bool -
Check whether the entire input sequence can be
matched against the regular expression.
regex
is the regular expression to match against.str
is the string to test. returns true if str can be matched entirely against regex. -
maybeExtractCountryCode(
String number, PhoneMetadata? defaultRegionMetadata, StringBuffer nationalNumber, bool keepRawInput, PhoneNumber phoneNumber) → int - 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:
-
maybeStripExtension(
StringBuffer number) → String - Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
-
maybeStripInternationalPrefixAndNormalize(
StringBuffer number, String possibleIddPrefix) → PhoneNumber_CountryCodeSource - 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.
-
maybeStripNationalPrefixAndCarrierCode(
StringBuffer number, PhoneMetadata metadata, StringBuffer? carrierCode) → bool - Strips any national prefix (such as 0, 1) present in the number provided.
-
normalize(
StringBuffer number) → 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.
-
normalizeDiallableCharsOnly(
String number) → 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).
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
parse(
String? numberToParse, String? defaultRegion) → PhoneNumber - Parses a string and returns it as a phone number in proto buffer format. The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the number (e.g. a leading 'Tel: ') and trims the non-number bits. It will accept a number in any format (E164, national, international etc), assuming it can be interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type '1800 MICROSOFT'.
-
parseAndKeepRawInput(
String numberToParse, String? defaultRegion) → PhoneNumber - Parses a string and returns it in proto buffer format. This method differs from parse in that it always populates the rawInput field of the protocol buffer with numberToParse as well as the countryCodeSource field.
-
replaceAllAndFormat(
String text, RegExp pattern, String format) → String -
replaceFirstAndFormat(
String text, Pattern pattern, String format) → String -
toString(
) → String -
A string representation of this object.
inherited
-
truncateTooLongNumber(
PhoneNumber number) → bool -
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.
number
a PhoneNumber object which contains a number that is too long to be valid. truncateTooLongNumber returns true if a valid phone number can be successfully extracted.
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Properties
- capturingDigitPattern → RegExp
-
final
- extnPatternsForMatching → String
-
final
- firstGroupPattern → RegExp
-
This was originally set to $1 but there are some countries for which the
first group is not used in the national pattern (e.g. Argentina) so the $1
group does not match correctly. Therefore, we use \d, so that the first
group actually used in the pattern will be matched.
final
- instance → PhoneNumberUtil
-
no setter
- nonDigitsPattern → RegExp
-
final
- plusCharsPattern → RegExp
-
final
- secondNumberStartPattern → RegExp
-
Regular expression of characters typically used to start a second phone
number for the purposes of parsing. This allows us to strip off parts of the
number that are actually the start of another number, such as for:
(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.
final
- unwantedEndCharPattern → RegExp
-
Regular expression of trailing characters that we want to remove. We remove
all characters that are not alpha or numerical characters. The hash character
is retained here, as it may signify the previous block was an extension.
final
Static Methods
-
characterToDigit(
String input) → int? -
extractPossibleNumber(
String number) → 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
_validStartCharPattern
. 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.number
is the string that might contain a phone number. extractPossibleNumber returns 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. -
formattingRuleHasFirstGroupOnly(
String nationalPrefixFormattingRule) → bool - Helper function to check if the national prefix formatting rule has the first group only, i.e., does not start with the national prefix.
-
getCountryMobileToken(
int countryCallingCode) → String - 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.
-
matchNationalNumber(
String number, PhoneNumberDesc numberDesc, bool allowPrefixMatch) → bool - Returns whether the given national number (a string containing only decimal digits) matches the national number pattern defined in the given PhoneNumberDesc message.
-
normalizeDigits(
String number, bool keepNonDigits) → StringBuffer -
normalizeDigitsOnly(
String number) → 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.
Constants
- maxLengthCountryCode → const int
- The maximum length of the country calling code.
- maxLengthForNsn → const int
- The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
- plusChars → const String
- plusSign → const String
- The PLUS_SIGN signifies the international prefix.
- regionCodeForNonGeoEntity → const String
- validPunctuation → const String
- Regular expression of acceptable punctuation found in phone numbers, used to find numbers in text and to decide what is a viable phone number. This excludes diallable characters. This consists of dash characters, white space characters, full stops, slashes, square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a placeholder for carrier information in some phone numbers. Full-width variants are also present.