Phone Number Formatter
Formatting and normalization for phone numbers, backed entirely by Google libphonenumber — the Java library on Android, its Objective-C port libPhoneNumber-iOS on iOS, both generated from the same metadata release (see PhoneNumberBackend).
There is no hand-written digit-grouping table here on purpose: per-country grouping rules, national trunk prefixes and example numbers all come from libphonenumber metadata, so adding a country to the dataset never requires touching formatting code.
All functions are pure and thread-safe. The underlying PhoneNumberUtil is an immutable singleton, but AsYouTypeFormatter is stateful, so formatAsYouType creates one per call rather than caching an instance that concurrent fields could corrupt.
Types
Result of parseInternational.
Functions
An example national number for country, e.g. "712 345 678" for Kenya, taken from libphonenumber metadata.
Expected number of national digits for country, derived from its example number.
Groups digits the way the international form of a number is written mid-typing — e.g. Kenya's "712 084 336" rather than the national form's "0712 084 336", or a NANP region's "712-345-6789" rather than the national form's "(712) 345-6789".
Maximum digits to accept for country, used to cap input.
Parses nationalNumber as a number in country into libphonenumber's own Phonenumber.PhoneNumber, returning null when it cannot be parsed at all (rather than throwing into composition).
Splits a pasted or prefilled string into the country it belongs to and its national digits.
International display form (+254 712 345 678), or null when parsing fails.
National display form (0712 345 678), or null when parsing fails.