Skip to content

Build a phone field

createPhoneInput turns a plain <input> into a phone field. This guide builds an international one. The widget handles the events, the value, the caret, and the history, while your renderStatus function draws the status line.

Type +14155550132. The field formats it live to +1 415-555-0132 and the status reads Valid: US +14155550132. Type +442071838750 instead and the field shows +44 20 7183 8750, because the calling code selects the region.

Edit in the middle of the number and the caret stays on the same digit while the groups reflow around it. Paste the number in any spelling that carries the calling code, +1 (415) 555-0132 or tel:+14155550132, and it lands as +1 415-555-0132. Backspace and Delete skip the formatting and remove the nearest digit in one press. Undo and redo use Cmd/Ctrl+Z and Cmd/Ctrl+Shift+Z. A number with too few digits shows TOO_SHORT.

The demo and the source are the same three files. The markup is an input and a status line. The script is one createPhoneInput call in international mode with an erasable plus. renderStatus draws the status from each emitted state.

<div id="phone-field">
<label for="phone-field-input">Phone number</label>
<input id="phone-field-input" type="tel" placeholder="+1 201-555-0123" />
<p class="phone-field-status"></p>
</div>

Covered events lists every input type PhoneInput handles, IME composition and drag-and-drop included. A region picker usually sits next to this field. Build a region picker adds one.