Skip to
Keyboard shortcuts

Use the up and down arrow keys to move between items. Press Alt+Shift+K to open this list again.

Alpha version out now. The API may still change.

PhoneInput

A box for a phone number, with an optional select for the country calling code. It keeps the number exactly as the person wrote or pasted it. It never formats the number, and by default it never refuses what is typed.

Package
@kvirn-ui/react
Testing
Not yet verified. Automated 2 of 5, Core 0 of 2, Release 0 of 3

When to use it#

  • Use it for a phone number the person types, in a Field with a visible label. It sets the phone keypad, switches off spell check, keeps the number left to right and tells autofill that this is a phone number.
  • It never formats, limits or checks the number. Check it in your form, and turn it into the international form (E.164, such as +46701740605) on the server.
  • For numbers from other countries, say in the help text to start with the country code. Or add a PhoneInput.Country select.
  • Not for a code sent by text message: use a OneTimeCode. Not for a quantity or an amount: use a NumberInput. Not for an identity or case number: use a TextInput with a mask.

Example#

If your number isn’t Swedish, start with the country code, for example +358.

Use cases#

Check the number after sending

The form checks the number on send. An error summary and an error under the box say how to fix it, and the number stays as written.

If your number isn’t Swedish, start with the country code, for example +358.

Warning: Don't forget

Say what is wrong and how to fix it, with an example, never only “invalid”. Show the error in text next to the box (3.3.1 Error Identification, 3.3.3 Error Suggestion).

A number from another country

The person picks the country. Changing it never prefixes or rewrites the number.

Phone number

The number without the country code, for example 070-174 06 05.

The form holds: SE,

Props in this example:

Warning: Don't forget

Give the country select its own label, or a screen reader user cannot tell what it is for (4.1.2 Name, Role, Value). Say in the help text whether the number goes with or without the country code.

The phone number of the other guardian

Switch autofill off for another person’s number, or the browser fills in the user’s own.

We use it only to reach them about this application.

Props in this example:

Leave out letters and stray signs

mask="telephone" accepts digits, spaces, dashes, brackets and a plus sign, leaves out the rest and says so politely. Digits from other scripts, such as Eastern Arabic, are refused: see Known issues.

Use digits, spaces, dashes, brackets and a plus sign, for example 070-174 06 05.

Props in this example:

  • mask on PhoneInput.Number

Warning: Don't forget

Wrap the page in a KvirnProvider. Without one, nothing says that a character was left out (4.1.3 Status Messages).

Accessibility#

What it does for you#

  • APG pattern: none needed. PhoneInput is a native <input type="tel">, a textbox. The name, description and state come from HTML and aria-describedby, as for TextInput.
  • Deviations: none from APG, because no APG pattern is used.
  • Native elements used: <input type="tel"> (PhoneInput.Number) with inputmode="tel", spellcheck="false", dir="ltr" and autocomplete="tel" (tel-national next to a country); optionally a native <select autocomplete="tel-country-code"> (PhoneInput.Country) in a <div> (PhoneInput.Root). No mask by default; mask="telephone" or your own mask adds no element and no role.

PhoneInput is a phone number in a Field (field.a11y.md): a TextInput with the attributes a phone number needs, set once (1.3.5). It never formats and never limits what the user writes: the value is their text. It is a native input, so the browser supplies the role, the keyboard, selection, paste and autofill.

PartElement / roleARIA / stateNotes
PhoneInput<input type="tel"> → textboxFrom the nearest Field: id, aria-describedby (description id, then error id), aria-invalid="true", aria-required="true", native disabled, data-invalid, data-required, data-disabledClasses kv-input kv-input--numeric kv-phone-input, and your className joins them. No pattern and no maxlength, ever
no Fieldnone addedNeeds aria-label or aria-labelledby, or a <label>. Dev warning (4.1.2, 3.3.2)
PhoneInput.Root<div>, no rolenoneLayout and the country only. Name the pair with a Fieldset legend (1.3.1)
PhoneInput.Country<select> → combobox (native)From its own Field: id, aria-describedby, aria-required, aria-invalid, disabled. In the number's Field: only disabledNo text of its own: its own Field.Label, or aria-label (dev warning phone-input-country-without-name, 4.1.2). Options such as Sweden (+46) on an English page (the country name is in the page's language), no flags (1.4.1)

Defaults, all overridable by a prop of yours: autoComplete="tel" (the full number, which is what autofill stores; use mobile tel, tel-national, or off for someone else's number), inputMode="tel", spellCheck={false}, dir="ltr".

What you need to do#

  • Put every PhoneInput in a Field with a Field.Label, or give it aria-label or aria-labelledby from your translations (4.1.2). Never use the placeholder as the label (3.3.2).
  • For international numbers without a PhoneInput.Country, say it in a help text: "If the number is not Swedish, start with the country code, for example +358." With one, name the select (its own Field.Label, or aria-label), and say in a help text that the number goes without the country code, or both ways are accepted.
  • Don't format the value and don't set pattern. Normalise to E.164 on the server.
  • Validate in your form after submit, say what's wrong and how to fix it in a Field.ErrorMessage ("Enter a phone number with digits, for example 070-174 06 05"), never only "invalid" (3.3.1, 3.3.3).
  • For someone else's number set autoComplete="off", so the user's own number isn't filled in.
  • Never block paste or autofill: a phone number is not a cognitive function test (3.3.8 applies to the code step that follows, see one-time-code.a11y.md), but people copy it from their contacts. A number the user gave earlier in the same process is filled in (defaultValue), not asked for again (3.3.7). Wrap the app in KvirnProvider if you use a mask, so a left-out character is announced (4.1.3).

Warning: Don't forget

Give every phone box a visible label in a Field. A placeholder is gone once the person types (4.1.2 Name, Role, Value; 3.3.2 Labels or Instructions).

Visual and modes#

PhoneInput looks like a TextInput, 20 characters wide and never wider than its container, so the look, focus indicator, target size, forced colours and reflow are the TextInput contract's.

  • Focus indicator: a visible outline, 3:1 against the adjacent colours (2.4.7; AAA 2.4.13 is not counted toward AA).
  • Target size: at least 24px high (2.5.8).
  • forced-colors behaviour: the input keeps a real border, and invalid is not colour alone.
  • reduced-motion behaviour: colour transitions only under no-preference.
  • RTL: dir="ltr", so +46 stays first; the box is still placed by the page's direction.

Focus management#

  • Initial focus: not moved. No autoFocus by default.
  • Trap: no.
  • Restore to: not applicable.
  • Never obscured by: PhoneInput renders no overlay. A sticky header needs the consumer's scroll-padding (2.4.11).

WCAG success criteria#

  • 1.3.1 Info and Relationships, 4.1.2 Name, Role, Value: through the Field (text-input.test.tsx, field.test.tsx).
  • 1.3.5 Identify Input Purpose: autocomplete="tel" by default (phone-input.test.tsx › sets type tel, inputmode tel, dir ltr and autocomplete tel, and yours wins); tel-national and tel-country-code with a country (phone-input.test.tsx › autocomplete is tel-national next to a Country and tel without, and the select is tel-country-code).
  • 1.4.1 Use of Color: no flags, the country is its name and calling code in text.
  • 2.1.1 Keyboard, 2.1.2 No Keyboard Trap: native input.
  • 3.2.2 On Input: typing never moves focus, and choosing a country never rewrites or prefixes the number (phone-input.test.tsx › changing the country never rewrites the typed number and reports the country and its calling code).
  • 3.3.2 Labels or Instructions: the Field's help text; a warning for your own mask without one (phone-input.test.tsx › a custom mask in a Field without a help text warns once, the default and telephone do not (3.3.2)).

Keyboard#

Focus
native
Selection follows focus
n/a
Arrows wrap
n/a
Shortcuts
none

All native: PhoneInput handles no keys itself and never calls preventDefault on one. A mask doesn't either, and never moves focus or auto-advances. The rows are TextInput's, and the masked rows apply with mask="telephone". In a Field, the Field.Label, the help text and the Field.ErrorMessage are not Tab stops (field.a11y.md). With a PhoneInput.Country there are two Tab stops, the select and then the number, in DOM order. The select's keys (Arrow keys, Home, End, type-ahead, Space or Alt+Down to open, Enter, Escape) are the browser's own native <select> and are never intercepted; choosing a country changes nothing in the number and never moves focus (3.2.2).

KeyWhereWhat happens
Tab / Shift+TabPhoneInputMoves focus to and from the input, in DOM order: one Tab stop. Nothing is rewritten on blur
Test: text-input.test.tsx › Tab moves through the inputs in DOM order, phone-input.test.tsx › keeps the user’s spaces, dashes, brackets and plus as typed and pasted, and blur rewrites nothing (%s)
CharactersPhoneInputTypes them. By default nothing is left out. mask="telephone" leaves out what isn't a digit, +, space, -, ( or ), and says so politely
Test: text-input.test.tsx › typing calls onValueChange with the value and the reason, and onChange too, phone-input.test.tsx › keeps the user’s spaces, dashes, brackets and plus as typed and pasted, and blur rewrites nothing (%s)
ArrowLeft / ArrowRight / Home / EndPhoneInputMove the caret (flips in RTL: the browser's own). Never intercepted
Test: text-input.test.tsx › ArrowLeft, ArrowRight, Home and End move the caret and are not intercepted
Control/Command+APhoneInputSelects all the text. Native
Test: text-input.test.tsx › Control/Command+A selects all the text
Control/Command+VPhoneInputPastes. Never blocked, and the pasted text is kept as pasted
Test: text-input.test.tsx › paste is not blocked, phone-input.test.tsx › a paste event is not cancelled and inserted text is kept as written; insertText stands in for the browser’s paste (%s), phone-input.test.tsx › keeps the user’s spaces, dashes, brackets and plus as typed and pasted, and blur rewrites nothing (%s)
EnterPhoneInput in a <form>Submits the form with the number as written. Native, never prevented
Test: text-input.test.tsx › Enter in a plain form submits it with the typed values (native)
EscapePhoneInputDoes nothing: the value and the focus stay
Test: text-input.test.tsx › Escape does nothing: the value and the focus stay
Tab / Shift+TabPhoneInput.CountryMoves focus to the select, then to the number (DOM order). Nothing is rewritten
Test: phone-input.test.tsx › Tab goes to the select and then to the number in DOM order, and Shift+Tab goes back
Arrow keys, Home, End, charactersPhoneInput.CountryNative <select>: move through and pick a country. Never intercepted; the typed number is not rewritten
Test: phone-input.test.tsx › changing the country never rewrites the typed number and reports the country and its calling code
No keyits Field.LabelA click on the label focuses the input (native <label for>)
Test: text-input.test.tsx › clicking the label focuses the input

Copy, cut and undo (Control/Command+C, X and Z) are native too. PhoneInput adds no shortcuts.

Announcements#

PhoneInput tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).

WhenWhat it saysMessage keyPoliteness
mask="telephone" or your own mask: a character is left outmask.characterNotAllowed allowedPolite

The text in all five languages

Change the text#

For your whole app, pass messages to KvirnProvider. For one PhoneInput, pass its messages prop.

<KvirnProvider messages={{ mask: { characterNotAllowed: '…' } }}>

Warning: Don't forget

Announcements need a KvirnProvider around your app, outside any <form>, or an Announcer of your own. Without one nothing is announced, and a development warning says so.

API reference#

import { PhoneInput, usePhoneInput, usePhoneInputRoot } from '@kvirn-ui/react'

PhoneInput.Number

Renders <input type="tel"> with the role textbox. It takes every attribute of an <input> except type, and passes ref to it. Put it in a Field: the label, help text and error are wired to it. It holds no form state: pass value and onValueChange, or defaultValue and name. Also exported as PhoneInputNumber. The default theme is described on Theming.

PropTypeDefaultDescription
valuestring–Controlled: the number from your form state, as the user wrote it, such as +46 70-174 06 05. Pair it with onValueChange.
defaultValuestring–Uncontrolled: the native input keeps the value, and a form submit sends it as written.
onValueChange(value: string, details: PhoneInputChangeDetails) => void–Called on every change with the number as shown. It is never formatted and never has the calling code added. details has reason, event, country and callingCode (digits only, such as 46) of the Root, and with a mask also unmaskedValue, isComplete and rejected. Make the number E.164 on the server.
maskMaskInput | falsefalseNo mask by default, so a number typed correctly is never refused. "telephone" leaves out everything except digits, +, space, - , ( and ), and says so politely. A { pattern }, a RegExp or a finished mask from masks replaces it. No mask formats the number.
announceRejectionsbooleantrueWith a mask: announces, politely and at most once every few seconds, when a character is left out. Needs a KvirnProvider.
messagesPartial<KvirnMessages['mask']>–With a mask: overrides the texts of the announcements for this input.
autoCompletestring'tel'The autofill purpose. tel is the full number, which is what autofill stores. Next to a PhoneInput.Country it is tel-national. Yours wins: mobile tel, or off for someone else’s number.
disabledbooleanfalseNative disabled. A disabled Field disables the input too.
refRef<HTMLInputElement>–Reaches the <input>.
Class or attributeValuesMeaning
kv-input, kv-input--numeric, kv-phone-inputalwaysThe part classes. kv-input--numeric uses tabular figures, and kv-phone-input makes the box 20 characters wide, never wider than its container.
kv-input--width-2, -4, -6, -10, -20class you addA width of your own. It wins over kv-phone-input. A width is a hint, never a limit.
type, inputmode, spellcheck, dir"tel", "tel", "false", "ltr"A phone input with the phone keypad, no spell check, and left to right so +46 stays first. Your own inputMode, spellCheck and dir win.
autocomplete"tel", or "tel-national" next to a CountryThe autofill purpose (1.3.5 Identify Input Purpose). The Number learns of a Country after mount, so server-rendered markup has "tel" until then.
id, aria-describedbyin a FieldFrom the Field. Your own aria-describedby ids come after the Field’s, and your own id is ignored in a Field: use controlId on Field.Root.
aria-invalid, aria-required"true" or absentIn a Field with invalid or required.
data-invalid, data-required, data-disabledpresent or absentThe state of the Field.
data-focused, data-focus-visiblepresent or absentThe input has focus, and the input has keyboard focus.
pattern, maxlengthneverPhoneInput never limits what the user writes.

PhoneInput.Root

Renders <div> with no role. Use it when you add a PhoneInput.Country: it holds the country that the select and the number share. It takes every attribute of a <div> and passes ref to it. Put it in a Fieldset whose legend names the pair. Also exported as PhoneInputRoot.

PropTypeDefaultDescription
countrystring–Controlled: the country as an ISO 3166-1 alpha-2 code (plus XK for Kosovo), such as SE. Pair it with onCountryChange, or the select can’t be changed. Without it: defaultCountry and the user’s choice, then the provider’s country, then the country the page’s language implies (Swedish SE, Finnish FI, Norwegian NO).
defaultCountrystring–Uncontrolled: the country the select starts on, before the user changes it.
onCountryChange(country: string, details: { reason: 'input'; event: ChangeEvent<HTMLSelectElement>; callingCode: string | undefined }) => void–Called when the user picks another country. It only reports: it never rewrites or prefixes the number. callingCode is digits only, such as 46.
refRef<HTMLDivElement>–Reaches the <div>.
Class or attributeValuesMeaning
kv-phone-input-groupalwaysThe layout class. The country select and the number sit side by side when there is room and stack when there is not.

PhoneInput.Country

Renders A native <select> of calling codes, such as “Sweden (+46)”: the country’s name in the page’s language and its calling code, the Root’s country first and the rest in alphabetical order. There are no flags. It holds no text of its own, so put it in its own Field with a Field.Label, or give it aria-label. It takes every attribute of a <select> except value, defaultValue and children. Also exported as PhoneInputCountry.

PropTypeDefaultDescription
onChangeChangeEventHandler<HTMLSelectElement>–The native change handler. It runs before the Root’s onCountryChange, which is the one to use to follow the country.
disabledbooleanfalseNative disabled. A disabled Field disables the select too.
refRef<HTMLSelectElement>–Reaches the <select>.
Class or attributeValuesMeaning
autocomplete"tel-country-code"Tells autofill this is the country code of a phone number (1.3.5 Identify Input Purpose).
kv-listbox-native, kv-phone-input-countryalwaysThe part classes: the look of a native select, sized to its content.
id, aria-describedby, aria-invalid, aria-required, disabledin its own FieldFrom its Field. In the number’s Field it takes only disabled, and a name from aria-label.

usePhoneInput

Use it for an <input> of your own. Call it in a component inside the Field, because it reads the nearest Field. It holds no value.

Options

PropTypeDefaultDescription
maskMaskInput | falsefalseNo mask by default, so a number typed correctly is never refused. "telephone" leaves out everything except digits, +, space, - , ( and ), and says so politely. A { pattern }, a RegExp or a finished mask from masks replaces it. No mask formats the number.
disabledbooleanfalseNative disabled. A disabled Field disables the input too.
onValueChange(value: string, details: TextInputChangeDetails) => void–Called with the text as the user wrote it on every change. It only reports. Make the number E.164 on the server.
announceRejectionsbooleantrueWith a mask: announces, politely and at most once every few seconds, when a character is left out. Needs a KvirnProvider.
messagesPartial<KvirnMessages['mask']>–With a mask: overrides the texts of the announcements for this input.

Result

PropTypeDefaultDescription
inputPropsPhoneInputPartProps–Spread on an <input>: the classes, type="tel", inputmode, spellcheck, dir, autocomplete, the Field’s id, aria-describedby and state, and the handlers. Put your own props after them.
maskMask | undefined–The mask that runs, before the locale is applied. undefined with no mask.
isInvalidboolean–Whether the Field is invalid.
isRequiredboolean–Whether the Field is required.
isDisabledboolean–Whether the input is disabled.
isFocusedboolean–Whether the input has focus.
isFocusVisibleboolean–Whether the input has keyboard focus.

usePhoneInputRoot

Holds the country of a phone number for your own markup. It holds no number and never rewrites one.

Options

PropTypeDefaultDescription
countrystring–Controlled: the country as an ISO 3166-1 alpha-2 code (plus XK for Kosovo), such as SE. Pair it with onCountryChange, or the select can’t be changed. Without it: defaultCountry and the user’s choice, then the provider’s country, then the country the page’s language implies (Swedish SE, Finnish FI, Norwegian NO).
defaultCountrystring–Uncontrolled: the country the select starts on, before the user changes it.
onCountryChange(country: string, details: { reason: 'input'; event: ChangeEvent<HTMLSelectElement>; callingCode: string | undefined }) => void–Called when the user picks another country. It only reports: it never rewrites or prefixes the number. callingCode is digits only, such as 46.

Result

PropTypeDefaultDescription
countrystring | undefined–The country that applies, in upper case, or undefined when no source says.
callingCodestring | undefined–Its calling code, digits only, such as 46.
selectCountry(country: string, event: ChangeEvent<HTMLSelectElement>) => void–Call it from the change event of your select. It reports to onCountryChange and, when the country is not controlled, remembers the choice.
rootPropsPhoneInputRootPartProps–Spread on the <div> that holds the parts: the class kv-phone-input-group.

Strings

These are the default texts in @kvirn-ui/i18n.

For your whole app, pass messages to KvirnProvider. For one PhoneInput, pass its messages prop.

PhoneInput has no strings of its own, and no keys. Without a mask it announces nothing. With one it announces the mask’s strings, and messages replaces them for one box. The label, help text and errors are yours, in your own translations.

mask.characterNotAllowed

Announced when a mask leaves out a character.

LanguageDefault text
SvenskaDet tecknet kan inte skrivas här.
SuomiTätä merkkiä ei voi kirjoittaa tähän.
Norsk bokmålDu kan ikke skrive det tegnet her.
Norsk nynorskDu kan ikkje skrive det teiknet her.
EnglishThat character can’t be entered here.

mask.maximumLength

Announced when a mask of your own leaves out a character because the box is full.

LanguageDefault text
SvenskaDu har skrivit alla 12 tecken.
SuomiOlet kirjoittanut kaikki 12 merkkiä.
Norsk bokmålDu har skrevet alle 12 tegnene.
Norsk nynorskDu har skrive alle 12 teikna.
EnglishYou’ve entered all 12 characters.

Known issues#

  • No mask by default. The telephone mask refuses Unicode digits (Eastern Arabic, full-width) and a dot, so a correctly typed number could be refused. Until the core mask maps them, mask="telephone" is the consumer's explicit choice.
  • Extensions. With mask="telephone", letters ("ankn. 123") are left out. Without a mask they are kept.
  • The select is optional. Without a PhoneInput.Country one box takes +358 …. Whether autofill fills the select from tel-country-code depends on the browser, since an option's text is the country name and its code, such as Sweden (+46). Test it in the browsers your users have.
  • tel-national is set after mount. The Number learns of the Country part in an effect, so server-rendered markup has tel until hydration.
  • Keyboard tests run in Chromium only. Test in Safari with your own assistive technology.

Information: Did you know?

If an issue here affects your service, list it in your accessibility statement with its workaround.

Testing#

The automated tests prove the keyboard behaviour, the names and states, that axe finds no violations in every story and theme, and, for the components they cover, that the stories hold up in forced colours, reduced motion, text spacing and a 320 pixel width. An Automated row passes on these tests alone. A Core or Release row passes only when an automated agent check and a person on the real assistive technology have both checked it. "agent-verified" means automated tests in the repository (with a virtual screen reader for the screen reader rows), not the real assistive technology.

AT + browser + OSAgent checkHuman checkResultNotes
Automated (re-runnable tests)
axe, WCAG 2.2 A and AA, every story, 4 themespassn/apassphone-input.stories.tsx, every story, 4 themes
Markup and ARIA (roles, names, ids, states)pendingn/apendingthe test has no axe check
Keyboard contract rows (Vitest browser)pendingn/apendingrows are tested on TextInput without a mask, not on PhoneInput
Focus order and managementpassn/apassphone-input.test.tsx asserts focus (toHaveFocus); first rule: Tab moves through the inputs in DOM order
Display modes (forced colours, 320px reflow, text spacing, reduced motion)pendingn/apendingnot in sweepComponents (vite.config.ts), so the four sweep projects do not run its stories
Core (required for beta)
NVDA + Chrome + Windowspendingpendingpending
VoiceOver + Safari + iOSpendingpendingpending
Release (before 1.0 and each minor)
JAWS + Chrome + Windowspendingpendingpending
TalkBack + Chrome + Androidpendingpendingpending
VoiceOver + Safari + macOSpendingpendingpending