When to use it#
- Use it for a short code the user receives and types once: a code from a text message, an email or an authenticator app, when signing in or confirming an action.
- Write a label that says where the code is, in the user’s words (“Code from the text message”), and a description above the boxes with the length, the groups and where to find it.
- Keep a submit button. If you check the code as it is entered, say so before the user types.
- Not for a password or a PIN the user keeps: use a TextInput with
type="password". A OneTimeCode is never a password field, so the user can see what they entered. - Not for a long identifier such as a personal identity number: use a TextInput with a mask.
Example#
We sent you a text message to confirm your mobile number. The code has 6 digits.
import { Field, OneTimeCode } from '@kvirn-ui/react'
import { useOneTimeCodeTexts } from './texts.ts'
const pattern = '999999'
export function SmsCode() {
const { texts } = useOneTimeCodeTexts()
return (
<Field.Root>
<Field.Label marker="none">{texts.smsLabel}</Field.Label>
<Field.Prose>
<p>{texts.plainHint}</p>
</Field.Prose>
<OneTimeCode.Root pattern={pattern}>
<OneTimeCode.Input name="code" />
{Array.from(pattern, (_, index) => (
<OneTimeCode.Slot key={index} index={index} />
))}
</OneTimeCode.Root>
</Field.Root>
)
}Use cases#
Sign in without BankID with a code from an email
Write the pattern the way the email groups the code: &&&&-&&&& for “ABCD-1234”. The dash is part of the value the boxes show, so read unmaskedValue when your service wants the code without it. Make your service leave out look-alike characters (0 and O, 1 and I), so nobody has to guess what they read.
You are signing in without BankID, so we sent a code to your email. The code has 8 letters and digits in 2 groups of 4. It never contains 0, O, 1 or I.
import { Field, OneTimeCode } from '@kvirn-ui/react'
import { useState } from 'react'
import { useOneTimeCodeTexts } from './texts.ts'
const pattern = '&&&&-&&&&'
export function TwoGroups() {
const { texts } = useOneTimeCodeTexts()
const [entered, setEntered] = useState<{ value: string; unmaskedValue: string }>()
return (
<Field.Root>
<Field.Label marker="none">{texts.emailLabel}</Field.Label>
<Field.Prose>
<p>{texts.emailHint}</p>
</Field.Prose>
<OneTimeCode.Root
pattern={pattern}
onComplete={(value, unmaskedValue) => setEntered({ value, unmaskedValue })}
>
<OneTimeCode.Input name="code" />
{Array.from(pattern, (_, index) => (
<OneTimeCode.Slot key={index} index={index} />
))}
</OneTimeCode.Root>
{entered === undefined ? null : (
<p>
{texts.entered} {entered.value}. {texts.withoutDash} {entered.unmaskedValue}
</p>
)}
</Field.Root>
)
}Props in this example:
patternon OneTimeCode.RootonCompleteon OneTimeCode.Rootindexon OneTimeCode.Slot
Information: Did you know?
Render one OneTimeCode.Slot for every position of the pattern, separators included. With fewer, a character is typed that nobody sees, and a development warning says so.
Confirm your mobile number as soon as the code is complete
onComplete starts your check. Use readOnly while it runs, not disabled, so focus stays, and keep the code in the field after a wrong-code error so the user can fix one digit. Focus stays in the field, so the example says “Checking the code” and then the error aloud.
import { Button, Field, OneTimeCode, useAnnouncer } from '@kvirn-ui/react'
import { useState } from 'react'
import { useOneTimeCodeTexts } from './texts.ts'
const pattern = '999999'
export function CheckedAsEntered() {
const { texts } = useOneTimeCodeTexts()
const { announce } = useAnnouncer()
const [value, setValue] = useState('')
const [isChecking, setIsChecking] = useState(false)
const [isWrong, setIsWrong] = useState(false)
return (
<form noValidate onSubmit={(event) => event.preventDefault()}>
<Field.Root invalid={isWrong}>
<Field.Label marker="none">{texts.smsLabel}</Field.Label>
<Field.Prose>
<p>{texts.smsHint}</p>
</Field.Prose>
<OneTimeCode.Root
pattern={pattern}
value={value}
onValueChange={(next) => {
setValue(next)
setIsWrong(false)
}}
onComplete={() => {
setIsChecking(true)
announce(texts.checking)
// Your own check goes here. This one always finds the code wrong.
setTimeout(() => {
setIsChecking(false)
setIsWrong(true)
// Focus stays in the field, so say the error aloud too.
announce(texts.wrong)
}, 1000)
}}
>
<OneTimeCode.Input name="code" readOnly={isChecking} />
{Array.from(pattern, (_, index) => (
<OneTimeCode.Slot key={index} index={index} />
))}
</OneTimeCode.Root>
<Field.ErrorMessage>{texts.wrong}</Field.ErrorMessage>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.submit}
</Button>
</form>
)
}Props in this example:
valueon OneTimeCode.RootonValueChangeon OneTimeCode.RootonCompleteon OneTimeCode.Root
Warning: Don't forget
Tell the user in the description, before they type, that the code is checked as soon as it is complete, and keep the submit button (3.2.2 On Input). Announcements need a KvirnProvider around your app. See What you need to do.
Confirm your mobile number in a plain form
Without value the native input keeps the code, and sending the form posts it under the input’s name, with its dash. Check it when the form is sent, move focus to the box and say what to do: “Enter all 6 digits of the code”.
import { Button, Field, OneTimeCode } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { useOneTimeCodeTexts } from './texts.ts'
const pattern = '999999'
export function PlainForm() {
const { texts } = useOneTimeCodeTexts()
const inputRef = useRef<HTMLInputElement>(null)
const [isIncomplete, setIsIncomplete] = useState(false)
const [attempts, setAttempts] = useState(0)
// Focus moves after the error has rendered, so the screen reader reads it with the input.
useEffect(() => {
if (attempts > 0 && isIncomplete) {
inputRef.current?.focus()
}
}, [attempts, isIncomplete])
return (
<form
noValidate
onSubmit={(event) => {
// A real form sends the data from here.
event.preventDefault()
const code = new FormData(event.currentTarget).get('code')
setIsIncomplete(typeof code !== 'string' || code.length < pattern.length)
setAttempts((count) => count + 1)
}}
>
<Field.Root invalid={isIncomplete}>
<Field.Label marker="none">{texts.smsLabel}</Field.Label>
<Field.Prose>
<p>{texts.plainHint}</p>
</Field.Prose>
<OneTimeCode.Root pattern={pattern} onValueChange={() => setIsIncomplete(false)}>
<OneTimeCode.Input ref={inputRef} name="code" />
{Array.from(pattern, (_, index) => (
<OneTimeCode.Slot key={index} index={index} />
))}
</OneTimeCode.Root>
<Field.ErrorMessage>{texts.incomplete}</Field.ErrorMessage>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.submit}
</Button>
</form>
)
}Props in this example:
onValueChangeon OneTimeCode.Root
Send a new code without losing the page
A text message can arrive late or not at all. Put “Send a new code” next to the field as one action that keeps the page and what the user has typed. Say in the description how long a code works, and say aloud that a new one is on its way.
import { Button, Field, OneTimeCode, useAnnouncer } from '@kvirn-ui/react'
import { useState } from 'react'
import { useOneTimeCodeTexts } from './texts.ts'
const pattern = '999999'
export function NewCode() {
const { texts } = useOneTimeCodeTexts()
const { announce } = useAnnouncer()
const [isSent, setIsSent] = useState(false)
return (
<form noValidate onSubmit={(event) => event.preventDefault()}>
<Field.Root>
<Field.Label marker="none">{texts.smsLabel}</Field.Label>
<Field.Prose>
<p>{texts.validHint}</p>
</Field.Prose>
{/* The code is not controlled here, and the button below never touches it: what the
user has typed stays, so they can still fix one digit. */}
<OneTimeCode.Root pattern={pattern}>
<OneTimeCode.Input name="code" />
{Array.from(pattern, (_, index) => (
<OneTimeCode.Slot key={index} index={index} />
))}
</OneTimeCode.Root>
</Field.Root>
<p>
<Button
type="button"
className="kv-button"
onClick={() => {
// Your own call that sends the code goes here.
setIsSent(true)
// Focus stays on the button, so say what happened aloud as well as on the page.
announce(texts.newCodeSent)
}}
>
{texts.sendNew}
</Button>
</p>
{isSent ? <p>{texts.newCodeSent}</p> : null}
<Button type="submit" className="kv-button--primary">
{texts.submit}
</Button>
</form>
)
}Warning: Don't forget
Say how long a code is valid, and never end the session or clear the form when it runs out (2.2.1 Timing Adjustable). Countdowns and “Send a new code” are not part of OneTimeCode: you build them, as here. See What you need to do.
Show why a character did not appear
A letter in a digits code is left out, and a screen reader says so politely. Someone who sees the boxes gets no sign unless you add one. onValueChange lists what was left out in details.rejected, so you can show the same words that messages announces.
We sent you a text message to confirm your mobile number. The code has 6 digits.
import { Field, OneTimeCode } from '@kvirn-ui/react'
import { useState } from 'react'
import { useOneTimeCodeTexts } from './texts.ts'
const pattern = '999999'
export function RefusedCharacters() {
const { texts } = useOneTimeCodeTexts()
const [hasRefusedLetter, setHasRefusedLetter] = useState(false)
return (
<Field.Root>
<Field.Label marker="none">{texts.smsLabel}</Field.Label>
<Field.Prose>
<p>{texts.plainHint}</p>
</Field.Prose>
<OneTimeCode.Root
pattern={pattern}
// The same words are announced politely and shown below, so what a screen reader user
// hears and what a sighted user reads match.
messages={{ characterNotAllowed: () => texts.onlyDigits }}
onValueChange={(_value, details) => {
// `rejected` lists what the mask dropped from this change, by reason. A full code is
// reported as `length`, so only `digits` means a non-digit was typed or pasted.
setHasRefusedLetter(details.rejected?.some(({ reason }) => reason === 'digits') ?? false)
}}
>
<OneTimeCode.Input name="code" />
{Array.from(pattern, (_, index) => (
<OneTimeCode.Slot key={index} index={index} />
))}
</OneTimeCode.Root>
{hasRefusedLetter ? <Field.HelpText>{texts.onlyDigits}</Field.HelpText> : null}
</Field.Root>
)
}Props in this example:
onValueChangeon OneTimeCode.Rootmessageson OneTimeCode.Root
Information: Did you know?
Keep the announcement on. The words you show are plain text, not a live region, so they are not announced a second time. Turn the announcement off with announceRejections only when you give the message yourself.
Accessibility#
What it does for you#
- APG pattern: none. A one-time code is one native text input. The name, description and state come from HTML and the Field (see the Field and TextInput contracts), and the masked typing rules from the mask engine.
- Deviations: none from APG. It is one native input, with boxes that only draw it. There is no auto-advance and no auto-submit.
- Native elements used:
<input type="text">(Input),<div>(Root, no role),<span aria-hidden="true">(Slot, and the separator).
A OneTimeCode shows a code sent by text message or email as a row of boxes, one per character, shaped by a pattern (999999, ****-****, AA-9999) with a dash drawn between the groups. Underneath it is one native input: autofill events, paste, undo and the screen reader work on that one field (tested); real SMS autofill, password managers and dictation are best checked by hand with your own users and assistive technology. The boxes are a drawing of its value, caret and selection, hidden from assistive technology. Nothing moves focus and nothing submits on its own (3.2.2).
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| OneTimeCode.Root | <div>, no role | none. data-complete, data-invalid, data-disabled, data-ready, data-character-count, data-separator-count | Class kv-one-time-code. Takes the options (pattern, value, defaultValue, onValueChange, onComplete, disabled, announceRejections, messages) and every attribute of a <div>. No role: it holds one control, and an unnamed group would only add noise. No form state |
| OneTimeCode.Input | <input type="text">, role textbox | name from the Field's label, description from its help text and error. aria-invalid, aria-required, native disabled, all from the Field. data-focused while it has focus, and data-focus-visible unless a pointer moved the focus there | Class kv-one-time-code-input. autocomplete="one-time-code", inputmode="numeric" (only when every symbol of the pattern is 9), autocapitalize="characters" (when no symbol is a or *), spellcheck="false", autocorrect="off", dir="ltr". No maxlength, no pattern, never type="password" |
| OneTimeCode.Slot | <span>, hidden from the a11y tree | aria-hidden="true". data-filled, data-active, data-caret="before" | "after", data-selected, data-invalid | Class kv-one-time-code-slot. Draws one character. Never focusable (a span with text), no name, role or description. Takes no pointer events in the default theme: every press goes to the input |
| Slot, separator | <span>, hidden from the a11y tree | aria-hidden="true". No data-* state | Class kv-one-time-code-separator. The pattern's -: it shows - always (it is the pattern, not the value), is never filled, active or selected, never focusable, takes no press |
useOneTimeCode | the same attributes, for your own elements | rootProps, inputProps, getSlotProps(index), slots (one per pattern position, each { kind, character, isFilled, isActive, caret, isSelected }), pattern, characterCount, isComplete, isReady | Options as the Root. Spread rootProps on the row, inputProps on one <input>, and getSlotProps(index) on each box |
Rules, each with an automated test:
- One field. The row has exactly one textbox. Its accessible name is the Field's visible label (2.5.3 Label in Name, A), and its description is the Field's help text, then the error. The slots are never in the name, the description or the tree.
- The attributes in the table above, on every input. The mask is
masks.oneTimeCode({ pattern }):9a digit,*a letter or digit,aa letter,Aan upper-case letter,&an upper-case letter or digit (all ASCII), and-a separator that sits between two of them. A pasted123 456,123-456or "Your code is 123456" ends as123456for999999, andabcd1234,abcd-1234andabcd 1234all end asabcd-1234for****-****. There is nomaxlengthand no rewrite during an IME composition. An invalid pattern (an unknown character, a-first, last or doubled, no character symbol) throws aRangeErrorthat names the character and its position. - Upper-case symbols upper-case what is typed. In
Aand&a typedais placed asA: the boxes show exactly what the input holds.aand*keep the case as typed. - The value includes the separator (
abcd-1234), as the boxes and the message show it.onValueChangedetails carryunmaskedValue(abcd1234) andonComplete(value, unmaskedValue)gets both. - One cell per pattern position.
slots,getSlotProps(index)andOneTimeCode.Slot indexshare one index: position _i_ of the pattern draws position _i_ of the value. A separator cell isaria-hiddenand has no state.isCompleteignores the separators. - State from the input. The slots draw what the input holds: its value, read again whenever the
valueprop or the hook's own state changes (so autofill, a controlledvalue, and a form reset are drawn as they are), and its caret and selection fromonSelect.data-activeis on the one character slot where the next character goes while the input has focus and nothing is selected: the first character slot at or after the caret, never a separator.data-caret="before"says the caret is before that slot's character."after"is on the last character slot of a complete code with the caret after it, and on the character slot before a-that is in the value when the caret sits just before that dash (the user stepped back over it), so the two sides of a separator don't look the same.data-selectedis on the filled slots a selection covers. None of them is set while the input has no focus. - Pattern facts on the Root.
data-character-count(the character symbols in the pattern:8for****-****) anddata-separator-count(the-:1, or0for none) are always rendered, on the server too. The theme reads them to size the row and to decide when to fall back. They are styling facts, not exposed to assistive technology, and the headless package sets no style from them. - Ready flag.
data-readyis set once the hook has started. It first runs the input's current value through the mask (writing it back only if it changed), so what the browser or a password manager filled in before the script ran is drawn as the mask would have shaped it, and an uncontrolled value never hides a character past the pattern. A controlledvalueis the consumer's and is drawn as it is, so one that is too long or has a separator hides characters from sighted users while a screen reader reads all of it: keep it to what the mask would produce. The mount step is silent: it calls neitheronValueChangenoronComplete, so a code autofilled before the script ran doesn't report completion (the submit button still covers it). The default theme draws the slots only then. - A press on a slot (a box, or a gap) focuses the input natively. A single click on an empty slot puts the caret at the end of the code, and on a filled slot before its character. A separator is not a target: a press on it or in the gap goes to the nearest character slot. A double click, a drag and a long press keep the browser's selection.
- No auto-advance, no auto-submit. Typing the last character moves no focus and submits nothing.
onComplete(value)is a callback for consumers who check early. - Field state.
data-invalidanddata-disabledcome from the nearest Field (or the Root'sdisabled), on the Root and on every slot. - Dev warnings: an Input or Slot outside a Root, a Slot whose index is not a position of the pattern (separators count), an Input with no accessible name, and an Input in a Field with no description (a
Field.Proseabove or aField.HelpTextunder: the length and the groups must be said, 3.3.2 Labels or Instructions, A).
What you need to do#
- A visible label that says where the code is, in the user's words ("Code from the text message"; "Code from your authenticator app"), not "OTP" or "verification code". The label is the accessible name (2.5.3 Label in Name, A).
- A description above the boxes, a
Field.Prosein the Field, with the length, the groups and where to find the code ("The code has 8 characters in two groups of 4. You find it in the text message we just sent"). The slots are hidden from screen readers and disappear in the fallback, so the description is the only place they learn the length and the groups (3.3.2 Labels or Instructions, A). A dev warning fires without one. - Errors in text, under the row, linked by the Field: "Enter all 6 digits of the code", "The code doesn't match the one we sent. Check the text message and enter the code again." Never blame, and keep the code in the field after a wrong-code error so the user can fix one digit (3.3.1 Error Identification, A; 3.3.3 Error Suggestion, AA).
- Keep a submit button. Never submit from
onCompletewithout telling the user in advance that the code is checked as soon as it's entered (3.2.2 On Input, A), and never clear the field on a wrong code. - After a wrong code, when focus is still in the field, announce the visible error text once, politely, through
useAnnouncer, and set the Field invalid. If focus was on the submit button, move focus to the field (its description reads the error) and don't announce as well. - While the code is being checked, use
readOnly, notdisabled, so focus stays, and say "Checking the code" through the Announcer. - Never
type="password", never block paste, and keepautocomplete="one-time-code". The user must see what they enter, and a password manager or SMS suggestion must be able to fill it (3.3.8 Accessible Authentication (Minimum), AA). - Write the
patternthe way the message groups the code (****-****for "ABCD-1234",999999for "481920"). A pattern that groups a code the message shows ungrouped, or the other way round, makes the user doubt what they see. Letters-and-digits codes should avoid look-alikes (0/O,1/I/l). - A service that wants the code without the dash reads
unmaskedValue(onValueChangedetails,onComplete's second argument), or strips the-from the submitted value. - Countdowns, "Send a new code" and timeouts are yours to build. The code's validity may be essential (2.2.1 Timing Adjustable, A), so say how long it is valid in the description, offer "Send a new code" as one action that keeps the page and its input, and never end the session or clear the form when a code expires.
- Everything in the TextInput and Field contracts still applies.
Warning: Don't forget
Write a visible label that says where the code is, and a description with its length and groups. The boxes are hidden from screen readers, so the description is the only place they learn the length (2.5.3 Label in Name, 3.3.2 Labels or Instructions).
Visual and modes#
- Focus indicator: on keyboard focus, the input's own ring around the whole row, with at least 3:1 contrast against the background (2.4.7 Focus Visible, AA; 2.4.13 Focus Appearance, AAA). It is set by
data-focus-visible, or by:focus-visiblebefore the script runs. A click shows no ring (an invalid field shows the ring on any focus, and keeps its error-coloured edge): the active box's edge shows the focus, and the plain field's edge turns heavier in the focus colour. The box where the next character goes also has a heavy focus-coloured edge and a static caret, and selected boxes a tinted fill with the same edge, never colour alone. - Target size: the input covers the whole row, so it clears 2.5.8 Target Size (Minimum, AA) in both densities, and in the default comfortable density it also clears 2.5.5 Target Size (Enhanced, AAA).
- Colour: the box edges have at least 3:1 contrast against the background (1.4.11 Non-text Contrast, AA). An invalid field has a heavier error-coloured edge on every box, never colour alone: the message under the row carries it. A disabled field has a dashed edge, and its characters are muted. Complete has no look of its own: a tick or green edge would read as "verified". The theme's contrast check covers every colour pair.
- Forced colours (the system's own colour scheme): the theme shows the plain input as a normal text field in the system's colours, with a heavier edge in the system text colour when invalid and a dashed grey edge when disabled. The focus edge and the keyboard ring use the system highlight colour, and a click's transparent outline is painted by the system. The slots are hidden. The forced-colours sweep checks that the input keeps a visible boundary and shows a focus indicator when it has focus.
- Reduced motion: the boxes' edge and fill change gradually only when the person has not asked for reduced motion. The caret never blinks, in any setting (2.2.2 Pause, Stop, Hide, A).
- Reflow (1.4.10 Reflow, AA): the boxes shrink, then the plain field shows instead of wrapping, so there is no horizontal scrolling at 320px width, in a card, at 200% text or at 400% zoom. Switching is CSS only: the same input keeps its value, caret and focus. The reflow sweep runs every story at 320 CSS px and fails on horizontal overflow, and the text-spacing sweep fails on a box that clips its text. 200% text and 400% zoom are checked by eye.
- Text spacing (1.4.12 Text Spacing, AA): the boxes don't depend on the input's text metrics, have no fixed height and are centred with flex, so characters are not clipped.
- Before the script runs (
data-readynot set) the plain input shows, so what is typed or autofilled meanwhile is visible as the browser draws it, with no mask and nomaxlength. When the script starts, that value goes through the mask once (separators and characters that don't fit are dropped, and it is written back only if it changed), so the boxes draw exactly what the field holds and the form never submits characters the boxes hide. A controlledvalueis the consumer's and is drawn as it is. A form reset does the same for the default value. - Right-to-left (RTL) pages: the code is an identifier, so the input has
dir="ltr"and the row of boxes reads left to right, at the start (the right) of the column. ArrowRight still moves to the next character.
Warning: Don't forget
If you restyle the boxes, keep their edges at least 3:1 against the background and keep the plain field that shows when the boxes don’t fit, so nothing scrolls sideways at 320px (1.4.11 Non-text Contrast, 1.4.10 Reflow).
Focus management#
- Initial focus: not moved. The component never focuses anything, including when the code is complete or when a wrong-code error shows (the page focuses the error summary or the field, as for any field).
- Trap: no.
- Restore to: not applicable. The input is always rendered, and never disabled while a code is checked: a disabled input loses focus, which lands on
body. UsereadOnlyand say "Checking the code" through the Announcer (see What you need to do). - Never obscured by: the focus ring is the input's own ring, drawn outside the whole row, and nothing in the row has overflow, so it is not clipped (2.4.11 Focus Not Obscured (Minimum), AA; 2.4.13 Focus Appearance, AAA). Consumers with a sticky header set
scroll-padding.
WCAG success criteria#
- 1.3.1 Info and Relationships (A), 3.3.2 Labels or Instructions (A), 4.1.2 Name, Role, Value (A): one native input, named by its label and described by its help text. The drawing is hidden.
- 1.3.2 Meaningful Sequence (A), 2.4.3 Focus Order (A): one Tab stop, in DOM order.
- 1.4.1 Use of Color (A), 1.4.11 Non-text Contrast (AA): the invalid width, the active and selected edges, the dashed disabled edge.
- 1.4.3 Contrast (Minimum) (AA), 1.4.4 Resize Text (AA), 1.4.10 Reflow (AA), 1.4.12 Text Spacing (AA): the fallback and the box-independent drawing.
- 2.1.1 Keyboard (A), 2.1.2 No Keyboard Trap (A), 2.1.4 Character Key Shortcuts (A): native keys only, no shortcuts.
- 2.2.2 Pause, Stop, Hide (A): not triggered: the drawn caret never blinks or moves on its own.
- 2.4.7 Focus Visible (AA), 2.4.11 Focus Not Obscured (Minimum) (AA), 2.4.13 Focus Appearance (AAA, not counted toward the AA bar): the ring around the whole row.
- 2.5.3 Label in Name (A), 2.5.5 Target Size (Enhanced) (AAA, not counted toward the AA bar) and 2.5.8 Target Size (Minimum) (AA): the label is the name, and the row is the target.
- 3.2.1 On Focus (A), 3.2.2 On Input (A): no focus moves and nothing submits.
- 3.3.1 Error Identification (A), 3.3.3 Error Suggestion (AA), 3.3.8 Accessible Authentication (Minimum) (AA): errors in text, and paste, autofill and password managers work with a visible code.
- 4.1.3 Status Messages (AA): refused characters are announced politely.
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- n/a
- Shortcuts
- none
| Key | Where | What happens |
|---|---|---|
| Tab | before the field | Moves focus into the code field. The whole row is one stop Test: one-time-code.test.tsx › Tab leaves the field, also when the code is complete: the only stop is the input |
| Tab | in the field | Moves focus to the next focusable element (Continue), never to another box, also when the code is complete Test: one-time-code.test.tsx › Tab leaves the field, also when the code is complete: the only stop is the input |
| Shift+Tab | in the field | Moves focus to the previous focusable element Test: one-time-code.test.tsx › Shift+Tab leaves the field to the previous focusable element, never to a box |
| Characters | in the field | Inserted at the caret and shown in its box. The caret moves to the next box, over the dash between groups, which the mask puts in as the next group's first character is placed. Focus stays when the code is complete, and nothing submits Test: one-time-code.test.tsx › typing across the separator: the dash goes in as the fifth character is placed |
| - | at a group break | Accepted once: the caret moves to the first box of the next group. A second - is refused, and so is a - anywhere elseTest: one-time-code.test.tsx › a typed dash after the group is accepted once, and not doubled |
| Lower-case letter | in an A or & position | Inserted as the capital, and the box shows the capital. a and * keep the case typedTest: one-time-code.test.tsx › AA-9999: lower case is upper-cased, in the field and in the boxes |
| A refused character | in the field | Not inserted. A polite message says which characters fit ("Only digits can be entered here") Test: one-time-code.test.tsx › a letter in a digits code is not inserted |
| Characters | code complete, caret at the end | Not inserted. A polite message says the code is complete ("You've entered all 6 characters") Test: one-time-code.test.tsx › a seventh digit is not inserted (no maxlength, the mask refuses it) |
| Control/Command+V | in the field | Pastes. Spaces, dashes and other text are removed, and the code fills the boxes, with the dash between the groups Test: one-time-code.test.tsx › three groups: a paste with or without dashes ends with them |
| Backspace | in the field | Deletes the character before the caret, also across the dash. Later characters move back one box Test: one-time-code.test.tsx › Backspace deletes before the caret and the later characters move back |
| Delete | in the field | Deletes the character after the caret Test: one-time-code.test.tsx › Delete deletes after the caret |
| ArrowLeft / ArrowRight | in the field | Moves the caret one character, shown by the active box. Native Test: one-time-code.test.tsx › ArrowLeft puts the caret before a filled character, and the active slot follows |
| ArrowLeft / ArrowRight | in the field, RTL page | The code reads left to right, so ArrowRight still moves to the next character and the next box on the right Test: one-time-code.test.tsx › arrows follow the code on an RTL page: ArrowRight is the next character |
| ArrowLeft / ArrowRight | in the field, at a separator | Steps over the dash in one press. The dash is never an active box: with the caret just before it, the caret is drawn after the last box of the group Test: one-time-code.test.tsx › ArrowLeft steps back over the dash in one press, then before the last box of the first group |
| Backspace / Delete | in the field, next to a dash | Deletes the character before or after the caret, across the dash. A dash that the mask puts back never makes the key do nothing Test: one-time-code.test.tsx › Backspace and Delete cross the separator |
| Home / End | in the field | Moves the caret before the first character, or after the last Test: one-time-code.test.tsx › Home and End move the caret to the ends |
| Shift+ArrowLeft / Shift+ArrowRight, Shift+Home / Shift+End | in the field | Extends the selection. The selected boxes are highlighted Test: one-time-code.test.tsx › Shift+ArrowLeft extends the selection one slot at a time |
| Control/Command+A | in the field | Selects the whole code. Every filled box is highlighted Test: one-time-code.test.tsx › Control+A selects the code: data-selected on every filled slot, and no active slot |
| Control/Command+Z | in the field | Undoes the last edit. Native Test: one-time-code.test.tsx › Control+Z undoes the last edit |
| ArrowUp / ArrowDown | in the field | Native caret movement only. Never changes the value Test: one-time-code.test.tsx › ArrowUp and ArrowDown never change the value |
| Enter | in the field | Submits the form, if it has a submit button (native implicit submission). Never prevented Test: one-time-code.test.tsx › no auto-advance and no auto-submit: focus stays, and the form does not submit |
| Pointer press | on a box or in a gap | Focuses the field. A press on an empty box puts the caret at the end of the code, and on a filled box before its character Test: one-time-code.test.tsx › a press is placed by the character box nearest to it: a separator and a gap are not targets |
| Pointer press | on a separator | Focuses the field. The dash takes no press: the caret goes to the nearer box, before its character Test: one-time-code.test.tsx › a press is placed by the character box nearest to it: a separator and a gap are not targets |
Every key is the native text field's, and the component prevents none of them: no key moves focus between boxes, and none is a shortcut. The ring is the input's, around the whole row, on keyboard focus.
Announcements#
OneTimeCode tells screen reader users about these changes without moving focus. Each message waits until the screen reader is quiet (polite) or interrupts it (assertive).
| When | What it says | Message key | Politeness |
|---|---|---|---|
| A character the mask refuses (a letter in a digits code) | Only digits can be entered here. | mask.characterNotAllowed | Polite |
| A character refused because the code is complete | You’ve entered all 6 characters. | mask.maximumLength | Polite |
The text in all five languages
Change the text#
For your whole app, pass messages to KvirnProvider. For one OneTimeCode, pass its messages prop.
<KvirnProvider messages={{ mask: { characterNotAllowed: 'Only digits can be entered here.' } }}>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 { OneTimeCode, Field, useOneTimeCode } from '@kvirn-ui/react'OneTimeCode.Root
Renders <div class="kv-one-time-code"> with no role: it holds one control, and an unnamed group would only add noise. It takes every attribute of a <div> and passes ref to it. Put it in a Field with a label and a Field.Prose. The default theme is described on Theming.
| Prop | Type | Default | Description |
|---|---|---|---|
pattern | string | '999999' | One symbol per position: 9 a digit, * a letter or digit, a a letter, A an upper-case letter, & an upper-case letter or digit, - a separator between two of them. ASCII only. An invalid pattern throws a RangeError, also in production. |
value | string | – | Controlled: the value from your state, with its separators (ABCD-1234). Pair it with onValueChange. |
defaultValue | string | – | Uncontrolled: the native input keeps the value, and a form submit sends it. |
onValueChange | (value: string, details: TextInputChangeDetails) => void | – | Called with the masked value on every change. details has reason, event and the mask’s unmaskedValue, isComplete and rejected. It only reports. |
onComplete | (value: string, unmaskedValue: string) => void | – | Called when a change leaves the code complete and different: the last character, a paste or an autofill. It never submits and never moves focus. |
disabled | boolean | false | Native disabled. A disabled Field disables the input too. |
announceRejections | boolean | true | Announces, politely and throttled, when the mask drops a character (4.1.3). Needs a KvirnProvider. |
messages | Partial<KvirnMessages['mask']> | – | Replaces the rejection messages for this code. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-one-time-code | always | The part class: the row. The default theme styles it. |
data-complete | present or absent | Every character slot is filled. |
data-invalid | present or absent | The Field is invalid. Also on every slot. |
data-disabled | present or absent | The Field or the disabled prop disables it. Also on every slot. |
data-ready | present or absent | The hook has started and read the input’s value. The theme draws the slots only then: until then it shows the plain input. |
data-character-count | number | The character symbols in the pattern (8 for ****-****). The theme reads it. |
data-separator-count | number | The - in the pattern (1 for ****-****, 0 for none). The theme reads it. |
OneTimeCode.Input
Renders <input type="text"> with the role textbox: the one native input, which takes the typing, paste, autofill and dictation. It takes every attribute of an <input> except type, value and defaultValue, and passes ref to it. Inside a Field it is named by the label and described by the Field’s text, and its own id is ignored.
| Class or attribute | Values | Meaning |
|---|---|---|
kv-one-time-code-input | always | The part class: the one native input. |
autocomplete | "one-time-code" | Always, with type="text", spellcheck="false", autocorrect="off" and dir="ltr". No maxlength, no pattern, never type="password". |
inputmode | "numeric" or absent | Only when every character symbol of the pattern is 9. |
autocapitalize | "characters" or absent | Unless a symbol is a or *. |
data-focused | present or absent | The input has focus, however it got it. |
data-focus-visible | present or absent | The input has keyboard focus. |
data-invalid, data-required, data-disabled | present or absent | From the Field, with aria-invalid, aria-required and native disabled. data-disabled also follows the disabled prop. |
OneTimeCode.Slot
Renders <span aria-hidden="true">: one drawn cell of the pattern. It is never focusable, and a press on it focuses the input. It takes every attribute of a <span> and passes ref to it.
| Prop | Type | Default | Description |
|---|---|---|---|
index | number | Required | The position in the pattern this slot draws, from 0 to pattern.length - 1. A - in the pattern is a separator slot, so render one slot per position, separators included. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-one-time-code-slot | on a character slot | Draws one character. aria-hidden="true", never focusable. |
kv-one-time-code-separator | on a separator slot | The pattern’s -. It has no state and is never filled, active or selected. |
data-filled | present or absent | The slot holds a character. |
data-active | present or absent | Where the next character goes, while the input has focus and nothing is selected. |
data-caret | "before" or "after" | On the active slot: the caret is before its character, or after the last one. |
data-selected | present or absent | The input’s selection covers this slot’s character. |
data-invalid | present or absent | The Field is invalid. |
useOneTimeCode
Options
| Prop | Type | Default | Description |
|---|---|---|---|
pattern | string | '999999' | One symbol per position: 9 a digit, * a letter or digit, a a letter, A an upper-case letter, & an upper-case letter or digit, - a separator between two of them. ASCII only. An invalid pattern throws a RangeError, also in production. |
value | string | – | Controlled: the value from your state, with its separators (ABCD-1234). Pair it with onValueChange. |
defaultValue | string | – | Uncontrolled: the native input keeps the value, and a form submit sends it. |
onValueChange | (value: string, details: TextInputChangeDetails) => void | – | Called with the masked value on every change. details has reason, event and the mask’s unmaskedValue, isComplete and rejected. It only reports. |
onComplete | (value: string, unmaskedValue: string) => void | – | Called when a change leaves the code complete and different: the last character, a paste or an autofill. It never submits and never moves focus. |
disabled | boolean | false | Native disabled. A disabled Field disables the input too. |
announceRejections | boolean | true | Announces, politely and throttled, when the mask drops a character (4.1.3). Needs a KvirnProvider. |
messages | Partial<KvirnMessages['mask']> | – | Replaces the rejection messages for this code. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
rootProps | OneTimeCodeRootPartProps | – | Spread on the row: class and the data-* the theme reads. |
inputProps | OneTimeCodeInputPartProps | – | Spread on one <input>: class, the autofill attributes, Field wiring, value and handlers, and the ref the hook needs. |
getSlotProps | (index: number) => OneTimeCodeSlotPartProps | – | Spread on the slot at a position of the pattern, separators included. |
slots | readonly OneTimeCodeSlotState[] | – | One entry per position: { kind, character, isFilled, isActive, caret, isSelected }. Use it to render the slots. |
value | string | – | The value the input shows now, with its separators. |
pattern | string | – | The pattern in use. |
characterCount | number | – | How many characters the code has: the pattern without its separators. |
isComplete | boolean | – | Every character slot is filled. |
isReady | boolean | – | The hook has started and read the input’s value. |
isInvalid | boolean | – | Whether the Field is invalid. |
isDisabled | boolean | – | Whether the input is disabled. |
Strings
These are the default texts in @kvirn-ui/i18n.
For your whole app, pass messages to KvirnProvider. For one OneTimeCode, pass its messages prop.
OneTimeCode has no strings of its own. It announces the strings of the mask (the part that decides which characters fit), and messages replaces them for one code.
mask.characterNotAllowed
Announced when a character the pattern refuses is typed, shown here for a digits code.
| Language | Default text |
|---|---|
| Svenska | Här kan du bara skriva siffror. |
| Suomi | Tähän voi kirjoittaa vain numeroita. |
| Norsk bokmål | Her kan du bare skrive sifre. |
| Norsk nynorsk | Her kan du berre skrive siffer. |
| English | Only digits can be entered here. |
mask.maximumLength
Announced when a character is refused because the code is complete.
| Language | Default text |
|---|---|
| Svenska | Du har skrivit alla 6 tecken. |
| Suomi | Olet kirjoittanut kaikki 6 merkkiä. |
| Norsk bokmål | Du har skrevet alle 6 tegnene. |
| Norsk nynorsk | Du har skrive alle 6 teikna. |
| English | You’ve entered all 6 characters. |
Known issues#
- Screen readers read the dash in a grouped value ("A B C D dash 1 2 3 4"). Accepted: the separator is part of the value the boxes show, and the help text explains the groups.
- Screen readers read a digits value as a number ("four hundred eighty-one thousand…") until the user moves through it by character. The same as any numeric field.
- Password-manager icons can cover the last box. Not detectable in CSS; check it with the password managers your users have.
- The browser's autofill tint shows in the narrow gaps between the boxes, under the opaque boxes. Accepted: it tells sighted users the code was filled in.
- Undo after the mask inserted a literal can't be kept without
execCommand. A grouped pattern (****-****) has a literal, the dash, so undo after the mask put it in can step back over it in two presses. A pattern without a separator has no literals, and undo is native. - Keyboard tests run in Chromium only. The keyboard rows are tested automatically in Chromium, not in WebKit (Safari's engine). 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 + OS | Agent check | Human check | Result | Notes |
|---|---|---|---|---|
| Automated (re-runnable tests) | ||||
| axe, WCAG 2.2 A and AA, every story, 4 themes | pass | n/a | pass | one-time-code.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | one-time-code.test.tsx › is one native text input, named by its label and described by the help text; expectNoA11yViolations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 23 rows, each names a test (one-time-code.test.tsx › Tab leaves the field, also when the code is complete: the only stop is the input) |
| Focus order and management | pass | n/a | pass | one-time-code.test.tsx asserts focus (toHaveFocus); first rule: Tab leaves the field, also when the code is complete: the only stop is the input |
| Display modes (forced colours, 320px reflow, text spacing, reduced motion) | pass | n/a | pass | the four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI |
| Core (required for beta) | ||||
| NVDA + Chrome + Windows | pending | pending | pending | |
| VoiceOver + Safari + iOS | pending | pending | pending | |
| Release (before 1.0 and each minor) | ||||
| JAWS + Chrome + Windows | pending | pending | pending | |
| TalkBack + Chrome + Android | pending | pending | pending | |
| VoiceOver + Safari + macOS | pending | pending | pending | |
| Component-specific | ||||
| Caret position after activation (centre press by Dragon, Voice Control, VoiceOver iOS) | pending | pending | pending | A press at a box's centre puts the caret before that character, or at the end of the code on an empty box |
What to check#
With a screen reader and the keyboard, try:
- Tab to the field: the label and the description (length, groups) are read. The field is one text box.
- Type the code: your own typing is heard, and nothing extra when it is complete.
- A letter in a digits code: a polite "Only digits can be entered here" is said, and nothing is inserted.
- Paste "123 456" and "Your code is 123456": both leave
123456. - On a phone, a code from a text message is offered by the keyboard or browser and fills the field.
- After a wrong code, focus stays and the error is read once.