When to use it#
- Use it for a short answer typed as text: a name, an email address, a phone number or a code. Put it in a Field with a visible label.
- Choose the
typeandautoCompletethat fit the question, so the keyboard and autofill help the user. - A code that keeps its leading zeros, such as a postal code or a case number, is a TextInput, with a
maskwhere its shape matters. - Not for a quantity or an amount: use NumberInput. Not for a longer answer: use Textarea. Not for a date: use DateInput.
- For a unit or an icon inside the box, use InputGroup.
Example#
import { Field, TextInput } from '@kvirn-ui/react'
import { useTextInputTexts } from './texts.ts'
export function DefaultTextInput() {
const { texts } = useTextInputTexts()
return (
<Field.Root required>
<Field.Label>{texts.fullName}</Field.Label>
<TextInput name="name" autoComplete="name" />
</Field.Root>
)
}Use cases#
Contact details with the right keyboard
The type gives phones the right keyboard for an email address or a phone number. Add autoComplete wherever the question asks for the user’s own data, so the browser can fill it in. type="number" and type="date" are not accepted. A number box drops leading zeros and changes on scroll, so use NumberInput. For a date, use DateInput.
import { Field, TextInput } from '@kvirn-ui/react'
import { useTextInputTexts } from './texts.ts'
export function InputTypes() {
const { texts } = useTextInputTexts()
return (
<>
<Field.Root required>
<Field.Label>{texts.email}</Field.Label>
<TextInput name="email" type="email" autoComplete="email" />
</Field.Root>
<Field.Root required>
<Field.Label>{texts.phone}</Field.Label>
<TextInput name="phone" type="tel" autoComplete="tel" />
</Field.Root>
<Field.Root>
<Field.Label>{texts.website}</Field.Label>
<TextInput name="website" type="url" autoComplete="url" />
</Field.Root>
</>
)
}Props in this example:
typeon TextInput
Warning: Don't forget
Set autoComplete on every box that asks for the user’s own data, such as name, email, tel or postal-code (1.3.5 Identify Input Purpose). Never block paste or autofill (3.3.8 Accessible Authentication (Minimum)).
Address details with a width that fits each answer
A box as wide as the expected answer tells the user how much to write. The width classes are 2, 4, 6, 10 and 20 characters, and never limit what can be typed.
import { Field, TextInput } from '@kvirn-ui/react'
import { useTextInputTexts } from './texts.ts'
export function Widths() {
const { texts } = useTextInputTexts()
return (
<>
<Field.Root required>
<Field.Label>{texts.houseNumber}</Field.Label>
<TextInput name="houseNumber" className="kv-input--width-4" />
</Field.Root>
<Field.Root required>
<Field.Label>{texts.postalCode}</Field.Label>
<TextInput
name="postalCode"
autoComplete="postal-code"
inputMode="numeric"
spellCheck={false}
className="kv-input--width-6"
/>
</Field.Root>
<Field.Root required>
<Field.Label>{texts.street}</Field.Label>
<TextInput name="street" autoComplete="street-address" className="kv-input--width-20" />
</Field.Root>
</>
)
}Use the text while the user types
Pass value and onValueChange when your code needs the text as it changes, for example to check it or show it elsewhere. The value then lives in your state, or in your form library’s. TextInput shows what it is given and only reports changes.
You typed:
import { Field, TextInput } from '@kvirn-ui/react'
import { useState } from 'react'
import { useTextInputTexts } from './texts.ts'
export function Controlled() {
const { texts } = useTextInputTexts()
const [value, setValue] = useState('')
return (
<>
<Field.Root required>
<Field.Label>{texts.fullName}</Field.Label>
<TextInput name="name" autoComplete="name" value={value} onValueChange={setValue} />
</Field.Root>
<p>
{texts.youTyped}: {value}
</p>
</>
)
}Props in this example:
valueon TextInputonValueChangeon TextInput
A form that is sent as a whole
Without value the native input keeps the text, and sending the form sends it by name. Start it with defaultValue, for example with something the user already told you, so they don’t type it twice (3.3.7 Redundant Entry). Read the values from FormData. KvirnUI checks nothing: after sending, say what is missing in a Field.ErrorMessage and move focus to the first box with an error. For a longer form, add an ErrorSummary.
import { Button, Field, TextInput } from '@kvirn-ui/react'
import { useEffect, useRef, useState } from 'react'
import { useTextInputTexts } from './texts.ts'
const valueOf = (data: FormData, name: string) => {
const value = data.get(name)
return typeof value === 'string' ? value.trim() : ''
}
export function PlainForm() {
const { texts } = useTextInputTexts()
const nameRef = useRef<HTMLInputElement>(null)
const emailRef = useRef<HTMLInputElement>(null)
const [nameError, setNameError] = useState<string | undefined>()
const [emailError, setEmailError] = useState<string | undefined>()
const [attempts, setAttempts] = useState(0)
const [sent, setSent] = useState<string | undefined>()
// Focus moves after the errors have rendered, so the screen reader reads them with the box.
useEffect(() => {
if (attempts > 0 && nameError !== undefined) {
nameRef.current?.focus()
} else if (attempts > 0 && emailError !== undefined) {
emailRef.current?.focus()
}
}, [attempts, nameError, emailError])
return (
<>
<form
noValidate
onSubmit={(event) => {
event.preventDefault()
const data = new FormData(event.currentTarget)
const name = valueOf(data, 'name')
const email = valueOf(data, 'email')
setNameError(name === '' ? texts.nameMissing : undefined)
setEmailError(email === '' ? texts.emailMissing : undefined)
setSent(name === '' || email === '' ? undefined : `${name}, ${email}`)
setAttempts((count) => count + 1)
}}
>
<Field.Root required invalid={nameError !== undefined}>
<Field.Label>{texts.fullName}</Field.Label>
<TextInput ref={nameRef} name="name" autoComplete="name" defaultValue="Anna Andersson" />
<Field.ErrorMessage>{nameError}</Field.ErrorMessage>
</Field.Root>
<Field.Root required invalid={emailError !== undefined}>
<Field.Label>{texts.email}</Field.Label>
<TextInput ref={emailRef} name="email" type="email" autoComplete="email" />
<Field.ErrorMessage>{emailError}</Field.ErrorMessage>
</Field.Root>
<Button type="submit" className="kv-button--primary">
{texts.send}
</Button>
</form>
<output>{sent === undefined ? null : `${texts.sent}: ${sent}`}</output>
</>
)
}Props in this example:
defaultValueon TextInput
Information: Implement like this
A form library’s props and ref pass through to the input, so its spreads and registers work next to TextInput.
A code with a fixed shape
A mask shapes what is typed and puts the space in. A character it can’t take is left out and announced politely. The country comes from the language set on KvirnProvider unless you pass it. The mask never says a value is wrong: you check it after the form is sent.
Five digits, for example 123 45
Without the space:
import { Field, TextInput } from '@kvirn-ui/react'
import { useState } from 'react'
import { useTextInputTexts } from './texts.ts'
export function MaskedCode() {
const { texts } = useTextInputTexts()
const [unmasked, setUnmasked] = useState('')
return (
<>
<Field.Root required>
<Field.Label>{texts.postalCode}</Field.Label>
<TextInput
name="postalCode"
mask={{ preset: 'postal-code', country: 'SE' }}
autoComplete="postal-code"
className="kv-input--width-6"
onValueChange={(_value, details) => setUnmasked(details.unmaskedValue ?? '')}
/>
<Field.HelpText>{texts.postalCodeHelpText}</Field.HelpText>
</Field.Root>
<p>
{texts.unmasked}: {unmasked}
</p>
</>
)
}Props in this example:
maskon TextInputonValueChangeon TextInput
Warning: Don't forget
A mask doesn’t explain its format: say it with an example in a Field.HelpText under the box. The announcements need a KvirnProvider around your app, see Announcements.
Your own input element
For markup of your own, useTextInput gives the class, the type, the Field’s id and aria attributes, and the handlers to spread on a native input. It reads the nearest Field too.
import { Field, useTextInput } from '@kvirn-ui/react'
import { useTextInputTexts } from './texts.ts'
export function OwnInput() {
const { texts } = useTextInputTexts()
const input = useTextInput({ type: 'email' })
return (
<Field.Root required>
<Field.Label>{texts.email}</Field.Label>
<input {...input.inputProps} name="email" autoComplete="email" />
</Field.Root>
)
}Props in this example:
typeon useTextInput (options)
Accessibility#
What it does for you#
- APG pattern: none needed. TextInput is a native
<input>with a text-liketype. There is no APG pattern for a text field: the name, description and state come from HTML andaria-describedby. - Deviations: none from APG.
type="number"andtype="date"are not accepted by design. - Native elements used:
<input type="text | email | tel | url | password | search">. A mask adds no element and no role.
TextInput is the text control of a Field (see the Field page). It is a native input: the browser supplies the role (textbox, searchbox), the keyboard, selection, paste and autofill. TextInput adds the Field's wiring and the part class.
| Part | Element / role | ARIA / state | Notes |
|---|---|---|---|
| TextInput | <input> → textbox (searchbox for type="search") | From the nearest Field: id, aria-describedby (description id, then error id), aria-invalid="true", aria-required="true", native disabled, data-invalid, data-required, data-disabled | Class kv-input. type is text (the default), email, tel, url, password or search. Your own aria-describedby ids are kept, after the Field's. data-focused while it has focus, and data-focus-visible only while that focus came from the keyboard (browsers also match :focus-visible on a click in a text input). Native required, readOnly, disabled and aria-invalid pass through |
| no Field | none added | Needs aria-label or aria-labelledby, or a <label>. Dev warning (4.1.2 Name, Role, Value, A; 3.3.2 Labels or Instructions, A) | |
type="number" or type="date" | – | Rejected by the type. At runtime: a dev warning says to use NumberInput or DateInput. It still renders what was asked for |
A quantity or an amount is a NumberInput, not a TextInput. A code with leading zeros (a case number, a postcode) stays a TextInput: <TextInput mask="digits" />, or inputMode="numeric" with spellCheck={false} for a plain one. No pattern (the browser's own message would appear in its language), and no key filtering by TextInput itself. A mask drops a character it can't take and announces it politely, and paste and autofill still work.
useTextInput gives the same inputProps for your own <input>: it reads the nearest Field too.
What you need to do#
- Put every TextInput in a Field with a Field.Label, or give it
aria-labeloraria-labelledbyfrom your translations (4.1.2 Name, Role, Value, A). - Pre-fill a value the user already gave earlier in the same process (3.3.7 Redundant Entry, A): the TextInput takes it as
defaultValueorvalue. - Never use the placeholder as the label (3.3.2 Labels or Instructions, A). Put an example in the help text (a
Field.HelpTextin the Field), not in the box. - Set
autoCompleteon every input that asks for the user's own data (name,email,tel,postal-code,bday): 1.3.5 Identify Input Purpose (AA). Neverautocomplete="off"on a password, and never block paste (3.3.8 Accessible Authentication (Minimum), AA). - Use NumberInput for a quantity or an amount, and a TextInput with a mask (or
inputMode="numeric"andspellCheck={false}) for a code. Don't usetype="number"ortype="date". Validate ranges and formats yourself and say what's wrong in a Field.ErrorMessage. - Choose a width class that fits the answer:
kv-input--width-2,-4,-6,-10,-20. Width is a help text, never a limit: nomaxlengthcomes from it. - Read-only is for staff tools showing a value the user can't change here. Say why in the help text. In a resident form, avoid both read-only and disabled.
- With a
mask, put the format and an example in a help text, aField.HelpTextin the Field (3.3.2 Labels or Instructions, A; a development warning checks it): the mask shapes input, it doesn't explain it. A help text is text: keep it short and plain, because its accessible description is only the help text's text content (see the Field page). Wrap the app inKvirnProviderso refused characters are announced (4.1.3 Status Messages, AA). - Validate in your form, after submit: the mask never says a value is wrong. Call
checks.personalIdentityNumber,checks.organisationNumberandchecks.ibanand write a specific message fromreason. Don't clamp numbers tominandmax: show your own help text fromisWithinRange. - Set
autoCompleteon masked fields yourself where a token exists (postal-code,tel,email).masks.letters()isn't for names: names have spaces, hyphens and apostrophes. - Don't pass an
idinside a Field: the Field's id wins, so the label stays associated (dev warning). Use<Field.Root controlId>.
Warning: Don't forget
Give every box a visible label in a Field. A placeholder is not a label: it disappears when the user types (3.3.2 Labels or Instructions). Without a name a screen reader says only that there is a text box (4.1.2 Name, Role, Value).
Visual and modes#
- Focus indicator: on keyboard focus, a ring at least 2px thick, set off from the box, with at least 3:1 contrast against the adjacent colours (2.4.7 Focus Visible, AA; 2.4.13 Focus Appearance, AAA). Before the script runs, the browser's
:focus-visibledraws it. A click shows focus as a thicker edge in the focus colour, with no ring, so it changes width as well as colour. The text doesn't move. An invalid box keeps its thick error edge when it has focus, and the ring shows on any focus, a click included. - Target size: at least 24 × 24 CSS px, even for the narrowest width class (2.5.8 Target Size (Minimum), AA). The default theme makes the box taller, and a little lower in compact density on wide screens (from 64rem), never under that threshold. Typed text keeps the normal body size in compact density. A story asserts that threshold.
- Boundary: the edge has at least 3:1 contrast against every surface the default theme uses, checked in every theme (1.4.11 Non-text Contrast, AA). Invalid: a thicker edge in the error colour, without moving the text. Disabled: a dashed edge, so state is never shown by colour alone (1.4.1 Use of Color, A).
- forced-colors behaviour (Windows contrast themes): the box keeps a real border in the system's button-border colour. An invalid box has a thicker border in the system text colour, and a disabled one a dashed border in the disabled-text colour. Focus turns the edge to the highlight colour at normal width (a thick edge alone means invalid there), and keyboard focus draws a highlight ring. The system paints an outline on a click, so a click shows a ring there too. The forced-colours sweep checks that every input keeps a visible boundary and shows a focus indicator when it has focus (1.4.11).
- reduced-motion behaviour: colour transitions only when the user allows motion, and the reduced-motion sweep checks that no animation keeps looping (2.3.3).
- Reflow and text spacing: no fixed widths beyond the width classes, which never grow wider than their container (1.4.10 Reflow, AA). The reflow sweep runs every story at 320 CSS px and fails on horizontal overflow. The width classes leave room for the extra letter spacing that 1.4.12 Text Spacing (AA) allows, so the expected answer stays visible, and the text-spacing sweep fails when a box clips its text.
- RTL: logical properties only.
Warning: Don't forget
If you restyle the box, keep its edge at 3:1 contrast against the surface (1.4.11 Non-text Contrast), keep a visible focus ring (2.4.7 Focus Visible), keep it at least 24 CSS pixels tall (2.5.8 Target Size (Minimum)), and show an invalid box by more than colour (1.4.1 Use of Color).
Focus management#
- Initial focus: not moved. No
autoFocusby default. - Trap: no.
- Restore to: not applicable.
- Never obscured by: TextInput renders no overlay. If your page has a sticky header, add
scroll-paddingso it never covers the focused box (2.4.11 Focus Not Obscured (Minimum), AA).
Warning: Don't forget
If your page has a header that stays at the top while scrolling, add scroll-padding so it never covers the focused box (2.4.11 Focus Not Obscured (Minimum)).
Masked input#
A TextInput with a mask (or useMask on your own <input>) shapes what the user types: it drops characters that can't be valid, inserts separators as the user types past them, and limits the length. mask is a name ("postal-code", with the country from the provider's locale), { preset, country? }, { pattern }, a RegExp or a masks.* mask, resolved in the input: the keys, attributes and announcements are the same for all of them. The control stays a native <input>: no role, no maxlength, no pattern, no placeholder characters in the value. The mask holds no form state and corrects nothing: min and max are reported as isWithinRange, and the checks.* helpers are called by your form.
| Action | Result | Test |
|---|---|---|
| Type an allowed character | Inserted at the caret. A literal is inserted after it only when the next character is typed | use-mask.test.tsx › a literal is inserted only when the next character is typed (5.1) |
| Type a literal at its spot | Accepted once, not doubled | use-mask.test.tsx › a typed literal at its spot is accepted once, not doubled (5.2) |
| Type a refused character | Not inserted, the caret stays. details.rejected says why, and the Announcer says it, at most once every few seconds per field | use-mask.test.tsx › typing a refused character inserts nothing, and the caret stays, use-mask.test.tsx › holding a key announces once: the rest is throttled per field |
| Paste, drop or autofill | Separators and refused characters are stripped, the rest fills the mask. Nothing is truncated early | use-mask.test.tsx › %s fills the mask and ends as 19900101-1234, use-mask.test.tsx › a paste with refused characters drops them, and nothing is cut early |
| Backspace / Delete | Always removes a character, also next to a literal | use-mask.test.tsx › Backspace next to a literal removes a character, and the caret stays (5.6), use-mask.test.tsx › Delete before a literal removes the next character (5.6) |
| Caret | Stays right after the character the user typed, also across a literal the mask inserts | use-mask.test.tsx › the caret stays right after a character typed in the middle (5.6) |
| IME or dead key | Left alone until compositionend: the raw text shows while composing, and the mask applies once | use-mask.test.tsx › nothing is rewritten while composing, and the mask applies at compositionend |
| Undo | Native. Undo can't go back past the last step the mask rewrote (inserted a literal or removed a refused character), because writing the value clears the history before it. The mask writes back only when it changed the value | use-mask.test.tsx › Control/Command+Z undoes typing that the mask did not rewrite, use-mask.test.tsx › Control/Command+Z after a step the mask rewrote leaves a valid value |
- Roles / ARIA: a native
<input>, no added role, state or property. Field wiring as above. - Attributes the preset suggests (your own props win):
inputMode,autoCapitalize,spellCheck={false}and, for identifiers,dir="ltr". A preset never setsautocomplete: the right token depends on the question (1.3.5 Identify Input Purpose, AA). RTL: an identifier stays left to right in a right-to-left page (use-mask.test.tsx › an identifier mask suggests inputMode, spellCheck and dir="ltr"). - Value and details:
onValueChange(value, details)gets the masked value, anddetails.unmaskedValue,isComplete,isWithinRange(number masks) andrejected. A controlledvalueis rendered as given and never rewritten: usemask.format()for a stored value. - Composition: while composing,
onValueChangereports the raw value without mask details, so a controlled field keeps following what the IME shows. Atcompositionendit reports once more, with theCompositionEventasdetails.event. - Numbers: the decimal separator is the provider's locale (a comma in sv, fi, nb and nn), whichever separator is typed. The value is never clamped.
- Types: a mask works on
text,tel,search,urlandpassword. Ontype="email"the browser has no selection API, so onlymasks.email()is accepted: another mask warns in development, and the caret goes to the end when the mask rewrites. - Dev warnings: a masked TextInput in a Field without a description (a
Field.HelpTextorField.Prosein the Field) or anaria-describedbyof its own (3.3.2 Labels or Instructions, A: the mask doesn't explain the format), a mask other thanmasks.email()ontype="email", a mask name that isn't one (no mask runs), and a country mask by name with no country from the instance, the provider or the locale (it only takes digits). Without aKvirnProvider, the first refused character warns once that nothing is announced. - Format in text (3.3.2 Labels or Instructions, A): the help text says the format with an example. The mask is never the only explanation.
WCAG success criteria#
- 1.3.1 Info and Relationships (A): the label, description and error are programmatically associated (
text-input.test.tsx › in a Field). - 1.3.5 Identify Input Purpose (AA):
autoCompletepasses through (text-input.test.tsx › passes autoComplete, inputMode and spellCheck for numbers). - 1.4.1 Use of Color (A), 1.4.3 Contrast (Minimum) (AA), 1.4.11 Non-text Contrast (AA): the invalid edge and message, text contrast and edge contrast.
- 1.4.10 Reflow (AA): the width classes never grow wider than their container (
text-input.stories.tsx › Widths). - 2.1.1 Keyboard (A): native input.
- 2.4.7 Focus Visible (AA): the focus ring.
- 2.4.13 Focus Appearance (AAA): the ring's thickness and contrast. Not counted toward the AA bar.
- 2.5.3 Label in Name (A): the visible label is the name.
- 2.5.8 Target Size (Minimum) (AA): the box is at least 24 × 24 CSS px (
text-input.stories.tsx › Default). - 3.2.2 On Input (A): typing never moves focus, and a full mask doesn't advance (
use-mask.test.tsx › Tab and Shift+Tab move through the masked inputs in DOM order). - 3.3.1 Error Identification (A) and 3.3.2 Labels or Instructions (A): through the Field. A mask never auto-fixes or clamps what the user entered, and dropped characters are reported (
text-input.test.tsx › onValueChange gets the masked value and the mask details, once per change). - 3.3.8 Accessible Authentication (Minimum) (AA): paste and autofill work, and no cognitive test is added. A mask normalises a pasted value instead of refusing it.
- 4.1.2 Name, Role, Value (A): native role, name,
aria-invalid,aria-required,disabled. - 4.1.3 Status Messages (AA): a refused character is announced politely through the Announcer (
use-mask.test.tsx › a refused character is announced politely, in the provider language (sv, fi and en)).
Keyboard#
- Focus
- native
- Selection follows focus
- n/a
- Arrows wrap
- n/a
- Shortcuts
- none
All native: TextInput handles no keys itself and never calls preventDefault on one. A mask doesn't either: it reads the value after the browser's edit and rewrites it only when it must, and never moves focus or auto-advances. The masked rows are in the Keyboard table and in Masked input above. NumberInput's rows, including that ArrowUp and ArrowDown never step a value, are on its own page. In a Field, the Field.Label, the help text (a Prose) and the Field.ErrorMessage are not Tab stops (see the Field page).
| Key | Where | What happens |
|---|---|---|
| Tab / Shift+Tab | TextInput | Moves focus to and from the input, in DOM order Test: text-input.test.tsx › Tab moves through the inputs in DOM order |
| Characters | TextInput | Types them. Without a mask nothing is filtered. A mask leaves out what it can't take, and says so politely Test: text-input.test.tsx › typing calls onValueChange with the value and the reason, and onChange too, text-input.test.tsx › numbers are text: leading zeros are kept and nothing is filtered, text-input.test.tsx › a mask shapes the value, adds no role, and keeps the Field wiring |
| ArrowLeft / ArrowRight / Home / End | TextInput | Move 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+A | TextInput | Selects all the text. Native Test: text-input.test.tsx › Control/Command+A selects all the text |
| Control/Command+V | TextInput | Pastes. Never blocked (3.3.8) Test: text-input.test.tsx › paste is not blocked |
| Enter | TextInput in a <form> | Submits the form (implicit submission). Native, never prevented Test: text-input.test.tsx › Enter in a plain form submits it with the typed values (native) |
| Escape | TextInput | Does nothing: the value and the focus stay Test: text-input.test.tsx › Escape does nothing: the value and the focus stay |
| Tab / Shift+Tab | Masked input | Moves focus to and from the input, in DOM order. Never moves on when the mask is full Test: use-mask.test.tsx › Tab and Shift+Tab move through the masked inputs in DOM order |
| Characters | Masked input | Types the ones the mask allows, inserts a literal as the user types past it, drops the rest and says so Test: use-mask.test.tsx › a literal is inserted only when the next character is typed (5.1), use-mask.test.tsx › typing a refused character inserts nothing, and the caret stays |
| Control/Command+V | Masked input | Pastes: separators and refused characters are stripped, the rest fills the mask. Never blocked Test: use-mask.test.tsx › %s fills the mask and ends as 19900101-1234 |
| Backspace / Delete | Masked input | Removes a character, also next to a literal. Never intercepted Test: use-mask.test.tsx › Backspace next to a literal removes a character, and the caret stays (5.6), use-mask.test.tsx › Delete before a literal removes the next character (5.6), use-mask.test.tsx › Backspace and Delete are not intercepted by the page |
| ArrowLeft / ArrowRight / Home / End | Masked input | Move the caret (flips in RTL: the browser's own). Never intercepted Test: use-mask.test.tsx › ArrowLeft, ArrowRight, Home and End move the caret and are not intercepted |
| ArrowUp / ArrowDown | Masked number | Native caret movement only. Never steps or changes the value Test: use-mask.test.tsx › ArrowUp and ArrowDown never change a masked number |
| Control/Command+A | Masked input | Selects all the text. Typing then replaces it and the mask starts over Test: use-mask.test.tsx › Control/Command+A selects all the text |
| Control/Command+Z | Masked input | Undo is native: it works for typing the mask didn't rewrite, and can't go back past the last step the mask rewrote Test: use-mask.test.tsx › Control/Command+Z undoes typing that the mask did not rewrite, use-mask.test.tsx › Control/Command+Z after a step the mask rewrote leaves a valid value |
| Dead key, IME | Masked input | Left alone until the composition ends, then the mask applies once Test: use-mask.test.tsx › nothing is rewritten while composing, and the mask applies at compositionend, use-mask.test.tsx › a composed character the mask accepts stays |
| Enter | Masked input in a <form> | Submits the form with the masked value. Native, never prevented Test: use-mask.test.tsx › Enter in the form submits it with the masked values (native) |
| Escape | Masked input | Does nothing: the value and the focus stay Test: use-mask.test.tsx › Escape does nothing: the value and the focus stay |
| No key | its Field.Label | A 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. TextInput adds no shortcuts.
Announcements#
TextInput 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 is refused (the allowed kind: digits, letters, letters and digits, other) | Only digits can be entered here. | mask.characterNotAllowed | Polite |
The mask is full and another character is refused (the length is the number of characters) | You’ve entered all 10 characters. | mask.maximumLength | Polite |
| A number mask has all its decimals and another digit is refused | No more decimals can be entered here. | mask.maximumDecimals | Polite |
The text in all five languages
Change the text#
For your whole app, pass messages to KvirnProvider. For one TextInput, 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 { TextInput, useTextInput } from '@kvirn-ui/react'TextInput
Renders <input type="text"> with the role textbox, or searchbox for type="search". It takes every attribute of an <input> and passes ref to it. Inside a Field, the Field’s id wins over yours. The default theme is described on Theming.
| Prop | Type | Default | Description |
|---|---|---|---|
type | 'text' | 'email' | 'tel' | 'url' | 'password' | 'search' | 'text' | The input type. number and date are not accepted: use NumberInput and DateInput. A search type gives the searchbox role. |
value | string | – | Controlled: the value from your form state. Pass it with onValueChange. |
defaultValue | string | – | Uncontrolled: the native input keeps the value, and a form submit sends it. |
onValueChange | (value: string, details: TextInputChangeDetails) => void | – | Reports each change. details has reason and event, and with a mask also unmaskedValue, isComplete, isWithinRange and rejected. onChange still works. |
mask | MaskInput | – | Shapes what the user types: a name such as "postal-code", { preset, country? }, { pattern }, a RegExp or a mask from masks. The input stays native. Say the format in a help text. |
announceRejections | boolean | true | With a mask: announces politely, at most once every few seconds, when it drops characters. Needs a KvirnProvider. |
messages | Partial<KvirnMessages['mask']> | – | With a mask: per-instance overrides for the rejection announcements. |
| Class or attribute | Values | Meaning |
|---|---|---|
kv-input | always | The part class. The default theme styles it. |
kv-input--width-2, -4, -6, -10, -20 | class you add | A width that fits the expected answer. Never a limit: no maxlength comes from it. |
kv-input--numeric | class you add | Tabular figures, for a code made of digits. Theme option. |
data-invalid | present or absent | The Field is invalid. |
data-required | present or absent | The Field is required. |
data-disabled | present or absent | The input is disabled, by the Field or its own disabled. |
data-focused | present or absent | The input has focus. |
data-focus-visible | present or absent | The input has keyboard focus. |
aria-invalid, aria-required, aria-describedby | from the Field | Set by the Field. Your own aria-describedby ids come after the Field’s. |
useTextInput
Options
| Prop | Type | Default | Description |
|---|---|---|---|
type | 'text' | 'email' | 'tel' | 'url' | 'password' | 'search' | 'text' | The input type. |
disabled | boolean | false | Native disabled. A disabled Field disables the input too. |
onValueChange | (value: string, details: TextInputChangeDetails) => void | – | Called with the new value on every change. It only reports. |
Result
| Prop | Type | Default | Description |
|---|---|---|---|
inputProps | TextInputPartProps | – | Spread on an <input>: class, type, the Field’s id and aria attributes, state and handlers. |
isInvalid | boolean | – | Whether the Field is invalid. |
isRequired | boolean | – | Whether the Field is required. |
isDisabled | boolean | – | Whether the input is disabled. |
isFocused | boolean | – | Whether the input has focus. |
isFocusVisible | boolean | – | Whether the input has keyboard focus. |
Strings
These are the default texts in @kvirn-ui/i18n.
For your whole app, pass messages to KvirnProvider. For one TextInput, pass its messages prop.
A TextInput has strings only with a mask: the announcements. The label and error texts are the Field’s.
mask.characterNotAllowed
Announced when the mask leaves out a character.
| 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 left out because the mask is full.
| Language | Default text |
|---|---|
| Svenska | Du har skrivit alla 12 tecken. |
| Suomi | Olet kirjoittanut kaikki 12 merkkiä. |
| Norsk bokmål | Du har skrevet alle 12 tegnene. |
| Norsk nynorsk | Du har skrive alle 12 teikna. |
| English | You’ve entered all 12 characters. |
mask.maximumDecimals
Announced when a digit is left out because the decimals are full.
| Language | Default text |
|---|---|
| Svenska | Du kan inte skriva fler decimaler. |
| Suomi | Desimaaleja ei voi kirjoittaa enempää. |
| Norsk bokmål | Du kan ikke skrive flere desimaler. |
| Norsk nynorsk | Du kan ikkje skrive fleire desimalar. |
| English | No more decimals can be entered here. |
Known issues#
- TextInput itself has no prefix, suffix or show-password button. InputGroup adds addons (
kr,€) and a Button inside the box: see its contract. - Masks: test with assistive technology. The throttle (three seconds), the clear-then-set message and the caret behaviour are worth testing with NVDA, VoiceOver, TalkBack and Dragon. Real IMEs, dead keys and dictation are tested by hand; the component test dispatches composition events.
- Masks: undo. When the mask rewrites the value (inserts a literal, removes a refused character), undo can't go back past that step: writing the value clears the browser's history before it. Accepted.
- Masks: no provider, no announcement.
KvirnProvideris required for announcements. - Masks:
type="email"has no caret control, so onlymasks.email()is supported on it. - Keyboard tests run in Chromium only. The keyboard rows run in Vitest browser mode on Chromium, not in WebKit. Test in Safari with your own assistive technology.
Information: Did you know?
If one of these affects your service, put it in your accessibility statement, with the 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 | text-input.stories.tsx, every story, 4 themes |
| Markup and ARIA (roles, names, ids, states) | pass | n/a | pass | text-input.test.tsx › the Field’s label is the name, its id links them, and the type stays text; expectNoA11yViolations |
| Keyboard contract rows (Vitest browser) | pass | n/a | pass | 19 rows, each names a test (text-input.test.tsx › Tab moves through the inputs in DOM order) |
| Focus order and management | pass | n/a | pass | text-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) | 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 |
What to check#
With a screen reader and the keyboard, try:
- Tab into a Field: the label, "required", help text and error are read.
- Paste and autofill work.
- In a masked box a refused character inserts nothing and is announced politely once, not repeated while the key is held.
- The caret stays after the character you typed when the mask inserts a space.
- Enter in a form submits it.