Agent Wranglers

LOC-55Recommended

Show and accept phone numbers in each country's format

Accept phone numbers as people write them in their country. Show each one in the reader's national or international format with a phone number library.

How to do it

"070-123 45 67" is a Swedish mobile number only once you know the country. Ask for the country with the number, or default it from the address or locale. Parse with libphonenumber or a port of it, and store the result as Store phone numbers in E.164 says. Show the national format to readers in the same country, and the international format to everyone else. Use type="tel" and autocomplete="tel" on the field, and never strip a leading + or 0 by hand.

Examples

JavaScript example

import { parsePhoneNumber } from 'libphonenumber-js';
const phone = parsePhoneNumber('070-123 45 67', 'SE');
phone.number;                 // '+46701234567'
phone.formatNational();       // '070-123 45 67'
phone.formatInternational();  // '+46 70 123 45 67'

Python example

import phonenumbers
from phonenumbers import PhoneNumberFormat
phone = phonenumbers.parse("070-123 45 67", "SE")
phonenumbers.format_number(phone, PhoneNumberFormat.E164)           # '+46701234567'
phonenumbers.format_number(phone, PhoneNumberFormat.NATIONAL)       # '070-123 45 67'
phonenumbers.format_number(phone, PhoneNumberFormat.INTERNATIONAL)  # '+46 70 123 45 67'

How to check

A unit test parses "070-123 45 67" with the country SE and gets +46701234567. It formats that number back as "070-123 45 67" for SE and as "+46 70 123 45 67" for other countries.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/localization/formatting/phone-number-formats">Agent Wranglers localization playbook</a>. In code you write, add a comment next to it with the same link.