Parse before you format

A string of national digits is ambiguous without a default country. Pass an explicit ISO country when the input does not start with a country calling code. If the user enters an international value beginning with +, let the parser derive the numbering region from maintained metadata.

Google's libphonenumber provides JavaScript support for parsing, formatting and validating international numbers. Choose a maintained package or binding whose metadata update process fits your application.

Keep canonical and display values separate

const parsed = parsePhoneNumber(input, selectedCountry);

const storedValue = parsed.number;          // +442079460018
const localLabel = parsed.formatNational(); // 020 7946 0018
const globalLabel = parsed.formatInternational();

The exact API depends on the library you choose, but the data flow should remain the same: parse with context, validate the claim you need, store E.164 and format at the presentation edge. Try the E.164 formatter to compare the output forms.

Use as-you-type formatting carefully

Incremental formatting can help users read long inputs, but it must preserve cursor position, pasted values and country changes. Do not reject an incomplete number while the user is still typing. Show a hard error on submission or when the input is clearly impossible.

Keep the country selector accessible by keyboard and text label. A flag alone does not communicate a numbering plan and cannot distinguish every territory.

Repeat important checks on the server

Client-side formatting improves usability; it is not a trust boundary. Parse and normalize again on the server before deduplication, storage or delivery. Pin library versions, update metadata deliberately and run regression fixtures for every supported region after an upgrade.

JavaScript test cases to include

  • National and international forms for each supported country.
  • Pasted spaces, parentheses, hyphens and non-breaking spaces.
  • A trunk prefix that must be removed and a significant zero that must remain.
  • One digit below and above valid boundaries.
  • Country changes after digits have already been typed.
  • An extension stored separately from the E.164 value.

Build the matrix with the phone-number testing checklist.