Skip to content

Build a phone field

createPhoneInput binds a plain <input> to a core input controller; this guide runs it as an international field. The PhoneInput handles the events, the value, the caret, and the history, while your renderStatus function draws the rest.

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

The rest behaves the way a real field should. The caret holds its digit through a mid-value edit while the groups reflow. Paste accepts any notation. Deletion runs backward, forward, or a word at a time. Undo and redo use Cmd/Ctrl+Z and Cmd/Ctrl+Shift+Z. A value that falls short reads 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, where the erasable plus renders only while the value carries one. 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 already handles, IME composition and drag-and-drop included. The field is one half of the classic widget. Build a region picker is the other half.