PhoneNumberFormatter

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

Link copied to clipboard
data class ParsedNumber(val country: Country, val nationalDigits: String, val countryWasDetected: Boolean)

Properties

Link copied to clipboard
const val E164_MAX_DIGITS: Int = 15

ITU-T E.164 maximum subscriber number length.

Functions

Link copied to clipboard

An example national number for country, e.g. "712 345 678" for Kenya, taken from libphonenumber metadata.

Link copied to clipboard

Expected number of national digits for country, derived from its example number.

Link copied to clipboard
fun formatAsYouType(digits: String, country: Country): String

Groups digits the way a user of country expects to see them, mid-typing.

Link copied to clipboard

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".

Link copied to clipboard

Maximum digits to accept for country, used to cap input.

Link copied to clipboard
fun PhoneNumberFormatter.parse(nationalNumber: String, country: Country): Phonenumber.PhoneNumber?

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).

Link copied to clipboard

Splits a pasted or prefilled string into the country it belongs to and its national digits.

Link copied to clipboard
fun toE164(nationalNumber: String, country: Country): String?

E.164 form (+254712345678), or null when nationalNumber cannot be parsed.

Link copied to clipboard
fun toInternational(nationalNumber: String, country: Country): String?

International display form (+254 712 345 678), or null when parsing fails.

Link copied to clipboard
fun toNational(nationalNumber: String, country: Country): String?

National display form (0712 345 678), or null when parsing fails.