Categorygithub.com/nyaruka/phonenumbers
modulepackage
1.5.0
Repository: https://github.com/nyaruka/phonenumbers.git
Documentation: pkg.go.dev

# README

☎️ phonenumbers

Build Status codecov GoDoc

golang port of Google's libphonenumber forked from libphonenumber from ttacon/libphonenumber. This library is used daily in production for parsing and validation of numbers across the world, so is well maintained. Please open an issue if you encounter any problems, we'll do our best to address them.

[!IMPORTANT] The aim of this project is strictly to be a port and match as closely as possible the functionality in libphonenumber. Please don't submit feature requests for functionality that doesn't exist in libphonenumber.

[!IMPORTANT] We use the metadata from libphonenumber so if you encounter unexpected parsing results, please first verify if the problem affects libphonenumber and report there if so. You can use their online demo to quickly check parsing results.

Version Numbers

As we don't want to bump our major semantic version number in step with the upstream library, we use independent version numbers than the Google libphonenumber repo. The release notes will mention what version of the metadata a release was built against.

Usage

// parse our phone number
num, err := phonenumbers.Parse("6502530000", "US")

// format it using national format
formattedNum := phonenumbers.Format(num, phonenumbers.NATIONAL)

Updating Metadata

The buildmetadata command will fetch the latest XML file from the official Google repo and rebuild the go source files containing all the territory metadata, timezone and region maps.

It will rebuild the following files:

  • gen/metadata_bin.go - protocol buffer definitions for all the various formats across countries etc..
  • gen/shortnumber_metadata_bin.go - protocol buffer definitions for ShortNumberMetadata.xml
  • gen/countrycode_to_region_bin.go - information needed to map a country code to a region
  • gen/prefix_to_carrier_bin.go - information needed to map a phone number prefix to a carrier
  • gen/prefix_to_geocoding_bin.go - information needed to map a phone number prefix to a city or region
  • gen/prefix_to_timezone_bin.go - information needed to map a phone number prefix to a city or region
% go install github.com/nyaruka/phonenumbers/cmd/buildmetadata
% $GOPATH/bin/buildmetadata

# Packages

# Functions

Build a mapping from a country calling code to the region codes which denote the country/region represented by that country code.
Returns true if the given number, exactly as dialed, might be used to connect to an emergency service in the given region.
Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting.
Formats a phone number in the specified format using default rules.
FormatByPattern formats a phone number in the specified format using client-defined formatting rules.
Formats a phone number using the original phone number format that the number is parsed from.
Formats a phone number in national format for dialing using the carrier as specified in the carrierCode.
Formats a phone number in national format for dialing using the carrier as specified in the preferredDomesticCarrierCode field of the PhoneNumber object passed in.
Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region.
Formats a phone number for out-of-country dialing purposes.
Formats a phone number for out-of-country dialing purposes.
Same as Format(PhoneNumber, PhoneNumberFormat), but accepts a mutable StringBuilder as a parameter to decrease object creation when invoked many times.
GetCarrierForNumber returns the carrier we believe the number belongs to.
GetCarrierWithPrefixForNumber returns the carrier we believe the number belongs to, as well as its prefix.
Returns the country calling code for a specific region.
Returns the mobile token for the provided country calling code if it has one, otherwise returns an empty string.
Gets a valid number for the specified region.
Gets a valid number for the specified country calling code for a non-geographical entity.
Gets a valid number for the specified region and number type.
GetGeocodingForNumber returns the location we think the number was first acquired in.
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.
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.
Gets the national significant number of the a phone number.
Returns the national dialling prefix for a specific region.
Gets the type of a phone number.
Returns the region code that matches the specific country calling code.
Returns the region where a phone number is from.
Returns a list with the region codes that match the specific country calling code.
GetSafeCarrierDisplayNameForNumber Gets the name of the carrier for the given phone number only when it is 'safe' to display to users.
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.
GetSupportedGlobalNetworkCallingCodes returns all global network calling codes the library has metadata for.
GetSupportedRegions returns all regions the library has metadata for.
GetTimezonesForNumber returns the names of timezones which we believe maps to the passed in number.
GetTimezonesForPrefix returns a slice of Timezones corresponding to the number passed or error when it is impossible to convert the string to int The algorythm tries to match the timezones starting from the maximum number of phone number digits and decreasing until it finds one or reaches 0.
Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT.
Returns true if the given number exactly matches an emergency service number in the given region.
Returns true if the supplied region supports mobile number portability.
Checks if this is a region under the North American Numbering Plan Administration (NANPA).
Takes two phone numbers as strings and compares them for equality.
Takes two phone numbers and compares them for equality.
Takes two phone numbers and compares them for equality.
Convenience wrapper around IsPossibleNumberWithReason().
Check whether a phone number is a possible number.
Check whether a short number is a possible number.
Check whether a short number is a possible number when dialed from the given region.
Tests whether a phone number matches a valid pattern.
Tests whether a phone number is valid for a certain region.
Tests whether a short number matches a valid pattern.
Tests whether a short number matches a valid pattern in a region.
Returns whether the given national number (a string containing only decimal digits) matches the national number pattern defined in the given PhoneNumberDesc message.
MaybeSeparateExtensionFromPhone will extract 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 along with the proceeding phone number.
NewBuilder creates and initializes a new Buffer using buf as its initial contents.
NewBuilderString creates and initializes a new Buffer using string s as its initial contents.
Normalizes a string of characters representing a phone number.
Parses a string and returns it in proto buffer format.
Parses a string and returns it in proto buffer format.
Same as ParseAndKeepRawInput(String, String), but accepts a mutable PhoneNumber as a parameter to decrease object creation when invoked many times.
Same as Parse(string, string), but accepts mutable PhoneNumber as a parameter to decrease object creation when invoked many times.
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.

# Constants

The prefix that needs to be inserted in front of a Colombian landline number when dialed from a mobile phone in Colombia.
Default values for NumberFormat fields.
Default values for PhoneMetadata fields.
Default values for PhoneMetadata fields.
Default values for PhoneMetadata fields.
Default values for PhoneMetadata fields.
Default values for PhoneNumber fields.
NOTES: FIXED_LINE_OR_MOBILE: In some regions (e.g.
MAX_INPUT_STRING_LENGTH caps input strings for parsing at 250 chars.
MAX_LENGTH_COUNTRY_CODE is the maximum length of the country calling code.
MAX_LENGTH_FOR_NSN: The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
MIN_LENGTH_FOR_NSN is the minimum and maximum length of the national significant number.
The country_code is derived NOT based on the phone number itself, but from the defaultCountry parameter provided in the parsing function by the clients.
The country_code is derived based on a phone number with a leading IDD, e.g.
The country_code is derived based on a phone number with a leading "+", e.g.
The country_code is derived based on a phone number without a leading "+", e.g.
Default value returned if this is not set, because the phone number was created using parse, not parseAndKeepRawInput.
The PLUS_SIGN signifies the international prefix.
UNKNOWN_REGION is the region-code for the unknown region.
This is defined by ICU as the unknown time zone.
We accept alpha characters in phone numbers, ASCII only, upper and lower case.
Regular expression of acceptable punctuation found in phone numbers.

# Variables

Separate map of all symbols that we wish to retain when formatting alpha numbers.
Only upper-case variants of alpha characters are stored.
For performance reasons, amalgamate both into one map.
Regular expression of valid domainname for the phone-context parameter, following the syntax defined in RFC3966.
Pattern to capture digits used in an extension.
Set of country codes that doesn't have national prefix, but it has area codes.
Default extension prefix to use when formatting.
A map that contains characters that are essential when dialling.
Regexp of all known extension prefixes used by different regions followed by 1 or more valid digits, for use when parsing.
Regexp of all possible ways to write extensions, for use when parsing.
A pattern that is used to determine if the national prefix formatting rule has the first group only, i.e., does not start with the national prefix.
The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the first group is not used in the national pattern (e.g.
Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES below) which are not based on *area codes*.
Map of country calling codes that use a mobile token before the area code.
Enum value maps for PhoneNumber_CountryCodeSource.
Enum value maps for PhoneNumber_CountryCodeSource.
In these countries, if extra digits are added to an emergency number, it no longer connects to the emergency service.
Regular expression of valid global-number-digits for the phone-context parameter, following the syntax defined in RFC3966.
Regular expression of characters typically used to start a second phone number for the purposes of parsing.
Pattern that makes it easy to distinguish whether a region has a unique international dialing prefix or not.
Regular expression of trailing characters that we want to remove.
We use this pattern to check if the phone number has at least three letters in it - if so, then we treat it as a number where some phone-number digits are represented by letters.
Regular expression of viable phone numbers.
We append optionally the extension pattern to the end here, as a valid phone number may have an extension prefix appended, followed by 1 or more digits.
Regular expression of acceptable characters that may start a phone number for the purposes of parsing.

# Structs

A Buffer is a variable-sized buffer of bytes with Read and Write methods.
<!ELEMENT numberFormat (leadingDigits*, format, intlFormat*)>.
If you add, remove, or rename fields, or change their semantics, check if you should change the excludable field sets or the behavior in MetadataFilter.
If you add, remove, or rename fields, or change their semantics, check if you should change the excludable field sets or the behavior in MetadataFilter.
<!ELEMENT phoneNumberMetadata (territories)>.
<!ELEMENT territory (references?, availableFormats?, generalDesc, noInternationalDialling?,fixedLine?, mobile?, pager?, tollFree?, premiumRate?,sharedCost?, personalNumber?, voip?, uan?, voicemail?)>.

# Type aliases

TODO(ttacon): leniency comments?.
The source from which the country_code is derived.