Online Playground
Browse tools

Format a phone number as the user types

Use the AsYouType class in libphonenumber-js to format phone numbers while typing. Includes a live demo, default country handling and cursor tips.

AsYouType formats a number one character at a time, so a user typing 4155552671 sees (415) 555-2671 appear as they go. This guide shows how to use it, with a live demo, and the one pitfall that trips people up.

Try AsYouType live

Try

Processed locally with libphonenumber-js. Nothing you enter is sent to a server.

Basic usage

Create an AsYouType instance with a default country, then call input with the full string each time. It returns the formatted version.

js
import { AsYouType } from 'libphonenumber-js'

new AsYouType('US').input('4155552671')
// '(415) 555-2671'

new AsYouType().input('+44207946')
// '+44 20 7946'

Format in an input handler

Create a new instance on each change and pass in the whole value. Do not reuse one instance for edits, because it remembers the previous input.

js
input.addEventListener('input', () => {
  input.value = new AsYouType('US').input(input.value)
})

Read the result as you type

The instance can tell you what it has understood so far, for example the country and whether the number is complete enough to be valid.

js
const ayt = new AsYouType('US')
ayt.input('415555')
ayt.getNumber()?.country // 'US'
ayt.getNumber()?.isValid() // false until complete

What it cannot do

AsYouType was designed for a numeric keypad, so it accepts digits and a leading plus sign. It does not support typing an extension: the characters after the number are ignored, and the library's documentation suggests a separate field for the extension. new AsYouType('US').input('2133734253 ext 12') returns (213) 373-4253.

Use reset() to clear an instance, and getTemplate() to see the pattern it is using. For (213) 373 it returns (xxx) xxx.

The pitfall: deleting characters

If you rewrite input.value on every keystroke, the cursor jumps to the end and deleting a bracket or space can feel stuck. For a production field, set the value only when it differs and restore the cursor position, or use a component that handles this for you.

Format a finished number instead

For a number that is already complete, format it with the Formatter tool or with phone.formatNational() and phone.formatInternational().

FAQ

Questions people ask

What does AsYouType do with an invalid number?

It formats as far as it can and leaves the rest as typed. It does not throw, so you can call it on partial or wrong input safely.

Does AsYouType need a country?

Only for numbers without a plus sign. If the input starts with +, the country is read from the calling code.

Should I store the formatted value?

No. Store the E.164 number and format it for display only.