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.

NumberInput

A box for a quantity or an amount. It accepts digits and the decimal mark of the page’s language, leaves out other characters and says so, and never changes the number with the arrow keys.

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

When to use it#

  • Use a NumberInput for a quantity or an amount the user types: a number of people in a booking, hours per week, a rent. A number mask (a rule for which characters the box accepts) leaves out letters and signs the number can’t have.
  • Put it in a Field with a visible label. Put the unit in the label, and with decimals put the format and an example in a help text under the box.
  • Choose a width that fits the answer, from kv-input--width-2 up to kv-input--width-20. A width is a hint, not a limit.
  • Not for a code that keeps its leading zeros, such as a postcode, a case number or a personal identity number: use a TextInput with a mask, or a number would drop the zeros.
  • Not for a date: use a DateInput.

Example#

Use cases#

Working hours per week, with a decimal

Some answers have a decimal mark, and it depends on the language of the page: a comma in Swedish, a point in English. The box writes the mark the way the page does, and a typed comma or point is read as the mark. Under the box, the example shows the plain number your form should send.

Enter the hours as a number, for example 37.5.

The value your form sends:

Props in this example:

Warning: Don't forget

The box doesn’t explain the decimal mark. Say it in a help text under the box, with an example, as here (3.3.2 Labels or Instructions). Send details.unmaskedValue to your server: with the number mask it is the plain number, such as 37.5, whatever the page shows.

Number of people in a booking, 1 to 8

A quantity has limits, but the box never clamps or corrects what the user typed. It reports whether the number is inside min and max. Your form decides when the user sends it, writes the error and moves focus to the box.

Enter a whole number from 1 to 8.

Props in this example:

Warning: Don't forget

The range is never announced, so say it in a help text under the box, as here (3.3.2 Labels or Instructions). The error then says what to enter (3.3.3 Error Suggestion). See What you need to do.

Business profit or loss last year

A result can be below zero: a loss. allowNegative accepts a leading minus sign, and a minus sign pasted from a document, also the typographic minus (−), is read too. Phones then show the text keyboard, because the number keyboard on iPhone has no minus sign, so say in the help text how to write it.

Write a loss with a minus sign, for example -8450.

Props in this example:

A monthly rent in whole kronor, with the unit in the box

A unit such as “kr” can sit inside the box, in an InputGroup addon. Screen readers (software that reads the screen aloud) skip the addon, so the label still says the unit: “Monthly rent in kronor”. grouping writes the digits in threes, so a long amount is easier to read.

Props in this example:

Total project costs pasted from a budget

Sometimes the mask is in the way: an amount pasted from a spreadsheet, or a figure in a format the mask doesn’t know. With mask={false} the box is a plain numeric text box. Nothing is left out or announced, and onValueChange reports no mask details, so you read and check the value yourself.

Paste or type the amount as it is. We read it when you send the form.

Props in this example:

Accessibility#

What it does for you#

  • APG pattern: none needed. NumberInput is a native text <input>, a textbox. It is deliberately not the APG spin button: there is no stepping with the arrow keys and no spinner buttons. The name, description and state come from HTML and aria-describedby, as for TextInput.
  • Deviations: none from APG, because no APG pattern is used. type="number" is not used by design: it changes its value on the mouse wheel and on ArrowUp and ArrowDown, drops leading zeros, rounds silently, shows spinners that are hard to hit, and reads the decimal mark by the browser's language and not the page's (the reasons GOV.UK gives).
  • Native elements used: <input type="text"> with inputmode and spellcheck="false". By default it also runs a number mask (a rule for which characters the box accepts and how the number is written: masks.number()); mask={false} runs none and a custom mask replaces it. A mask adds no element and no role.

NumberInput is a quantity or an amount in a Field: a TextInput with a number mask built in, in the provider's language. It is a native input, so the browser supplies the role (textbox), the keyboard, selection, paste, autofill and undo. NumberInput adds the Field's wiring, the number mask and the part classes. The mask is optional: mask={false} makes it a plain numeric text box (same role, keys and Field wiring, nothing left out), and another mask replaces the number mask. For a code with leading zeros (a postcode, a case number) use a TextInput with a mask: a number would drop the zeros.

PartElement / roleARIA / stateNotes
NumberInput<input type="text"> → 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, and your className joins them. Never type="number" and never a spinbutton: min and max are props that are reported, not attributes (they're invalid on a text input). inputmode follows the mask: by default (the number mask) numeric, decimal with decimals, text when negatives are allowed (iOS numeric pads have no minus sign); with mask={false} the same values, read from the decimals and allowNegative props; with a custom mask, the one that mask suggests (mask.attributes). spellcheck="false". data-focused while it has focus, and data-focus-visible only for keyboard focus
no Fieldnone addedNeeds aria-label or aria-labelledby, or a <label>. Development warning (4.1.2 Name, Role, Value, A; 3.3.2 Labels or Instructions, A)
in an InputGroup.Root, with an Addonthe Addon is aria-hidden="true"A unit such as "kr" is only a visual repeat: the label must say it ("Monthly rent in kronor")

By default (no mask prop) these props become the number mask, in the provider's locale: decimals (default 0: no decimal mark), allowNegative (default false), grouping (default false), min and max. The decimal mark is the one of the page's language (a comma in sv, fi, nb and nn, a point in en), and a typed , or . is read as that mark. onValueChange(value, details) gets details.unmaskedValue (the machine form, -1234.5), details.isWithinRange (min and max), isComplete and rejected. With mask={false} none of these props shapes the value (the keypad still follows decimals and allowNegative; no unmaskedValue, isWithinRange, isComplete or rejected: only reason and event), and with a custom mask the details are that mask's. A range is reported, never enforced: the value is never clamped or corrected, so the user's entry never changes without notice. Your form says what's wrong and gives the allowed range in a Field.ErrorMessage (3.3.1 Error Identification, A; 3.3.3 Error Suggestion, AA), and states the range in the help text before input (3.3.2 Labels or Instructions, A).

useNumberInput gives the same inputProps for your own <input>: it reads the nearest Field too, and returns format and unmask for the provider's locale.

What you need to do#

  • Put every NumberInput in a Field with a Field.Label, or give it aria-label or aria-labelledby from your translations (4.1.2 Name, Role, Value, A). Never use the placeholder as the label (3.3.2 Labels or Instructions, A).
  • With decimals above 0, put the format and an example in a help text, a Field.HelpText under the control: "In kronor, for example 1 250,50" (3.3.2 Labels or Instructions, A; a development warning checks it). The mask takes the decimal mark of the page's language, but it doesn't explain it.
  • Put the unit in the label ("Monthly rent in kronor") or the help text. To also show it in the box, use an InputGroup.Addon: it is hidden from screen readers, so the label must still say it.
  • Set autoComplete where a token exists, and never block paste (3.3.8 Accessible Authentication (Minimum), AA, when the number is part of signing in). Don't set pattern: it triggers the browser's validation message, in the browser's language.
  • Validate in your form, after submit, and say what's wrong and how to fix it in a Field.ErrorMessage (3.3.1 Error Identification, A; 3.3.3 Error Suggestion, AA). min and max are only reported in details.isWithinRange: show your own help text, and never clamp.
  • Choose a width class that fits the answer: kv-input--width-2, -4, -6, -10, -20. A width is a hint, never a limit.
  • Wrap the app in KvirnProvider, so a left-out character is announced (4.1.3 Status Messages, AA) and the decimal mark follows the page's language.
  • Don't pass an id inside a Field: the Field's id wins. Use <Field.Root controlId>.

Warning: Don't forget

Give every NumberInput a visible label in a Field. Without a name a screen reader user can’t tell what the box is for, and a placeholder is gone as soon as the user types (4.1.2 Name, Role, Value; 3.3.2 Labels or Instructions).

Visual and modes#

NumberInput renders the kv-input part of TextInput with kv-input--numeric, so the look, focus indicator, target size, boundary, forced colours and reflow are the TextInput contract's (Visual and modes). In short:

  • Focus indicator: a ring with at least 3:1 contrast against the colours next to it, on keyboard focus (2.4.7 Focus Visible, AA; 2.4.13 Focus Appearance, AAA). An invalid box shows the ring on any focus, including a click, and keeps its error-coloured edge.
  • Target size: at least 24px high (2.5.8 Target Size (Minimum), AA).
  • Forced colours (the system's own colour scheme): the input keeps a real border, and invalid is not shown by colour alone.
  • Reduced motion: colours change gradually only when the person has not asked for reduced motion.
  • Right-to-left (RTL) pages: the layout uses logical properties only. The arrow keys are the browser's own. A negative number's minus sign: see Known issues.

Warning: Don't forget

If you restyle the box, keep a focus ring with at least 3:1 contrast against what is next to it, and keep an invalid box recognisable by more than colour: the error text carries it (2.4.7 Focus Visible, 1.4.1 Use of Color).

Focus management#

  • Initial focus: not moved. No autoFocus by default.
  • Trap: no.
  • Restore to: not applicable.
  • Never obscured by: NumberInput renders no overlay. A sticky header needs the consumer's scroll-padding (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)).

WCAG success criteria#

  • 1.3.1 Info and Relationships (A): the label, help text and error are programmatically associated (number-input.test.tsx › the label names it, the help text and the error describe it, and the state is on it).
  • 1.3.5 Identify Input Purpose (AA): only when the number is about the user and has an autocomplete token (postal-code, bday-year, cc-number); autoComplete passes through. An amount or a quantity has no token, so 1.3.5 doesn't apply to it (number-input.test.tsx › forwards its ref and native props, and the part classes join a consumer’s).
  • 2.1.1 Keyboard (A), 2.1.2 No Keyboard Trap (A): native input, and ArrowUp and ArrowDown are never taken (number-input.test.tsx › ArrowUp and ArrowDown never change the value).
  • 2.5.3 Label in Name (A): the visible label is the name.
  • 3.2.2 On Input (A): typing never moves focus, and a complete number doesn't advance.
  • 3.3.1 Error Identification (A), 3.3.2 Labels or Instructions (A) and 3.3.3 Error Suggestion (AA): through the Field, its help text and your error message. A range is reported, never enforced or clamped (number-input.test.tsx › min and max are reported as isWithinRange, never enforced).
  • 3.3.8 Accessible Authentication (Minimum) (AA): only when the number is part of signing in (a PIN, a code); paste and autofill work (number-input.test.tsx › paste is not blocked: 1 250,50 and 1250.50 both read).
  • 1.4.11 Non-text Contrast (AA), 2.4.7 Focus Visible (AA), 2.5.8 Target Size (Minimum) (AA): the input is TextInput's kv-input, so these are the TextInput contract's (Visual / modes); NumberInput adds no test of its own.
  • 2.4.11 Focus Not Obscured (Minimum) (AA): NumberInput renders no overlay; a sticky header needs your scroll-padding.
  • 4.1.2 Name, Role, Value (A): a native textbox with name, aria-invalid, aria-required and disabled (number-input.test.tsx › renders a native text box, not a spinbutton, with no min, max or pattern attribute).
  • 4.1.3 Status Messages (AA): a left-out character is announced politely through the Announcer, and a digit past the decimals says so and not that the field is full (number-input.test.tsx › a letter is left out and announced politely, in the provider language (%s), number-input.test.tsx › a digit past the decimals is left out and announced as decimals, not as a full field (%s)).

Keyboard#

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

All native: NumberInput handles no keys itself and never calls preventDefault on one. It is a text box, so ArrowUp and ArrowDown move the caret and never step the value. The mask reads the value after the browser's edit and rewrites it only when it must, and never moves focus or auto-advances. In a Field, the Field.Label, the help text and the error are not focusable and have no keys.

KeyWhereWhat happens
Tab / Shift+TabNumberInputMoves focus to and from the input, in DOM order. Never moves on by itself when the number is complete
Test: number-input.test.tsx › Tab and Shift+Tab move focus to and from the input, in DOM order
CharactersNumberInputDefault mask: types digits, and the decimal mark and a leading minus sign when the props allow them; leaves out the rest and says so politely. mask={false}: types anything, nothing is left out or announced. Custom mask: what that mask takes, with its announcements
Test: number-input.test.tsx › a whole number takes digits only: a letter and a decimal mark are left out, number-input.test.tsx › mask={false} is a plain numeric text box: nothing is left out, and no mask details are reported, number-input.test.tsx › a name replaces the number mask, with that mask’s unmaskedValue
Control/Command+VNumberInputPastes: 1 250,50, 1250.50 and 1 250,50 are all read, and written the way the page writes a number. Never blocked
Test: number-input.test.tsx › paste is not blocked: 1 250,50 and 1250.50 both read
ArrowLeft / ArrowRight / Home / EndNumberInputMove the caret (flips in RTL: the browser's own). Never intercepted
Test: number-input.test.tsx › ArrowLeft, ArrowRight, Home and End move the caret and are not intercepted, number-input.test.tsx › ArrowLeft and ArrowRight move the caret in a right-to-left page and are not intercepted
ArrowUp / ArrowDownNumberInputNative caret movement only. Never steps, rounds or changes the number
Test: number-input.test.tsx › ArrowUp and ArrowDown never change the value
Backspace / DeleteNumberInputRemove a character, also next to a group separator. Never intercepted
Test: number-input.test.tsx › Backspace and Delete remove a character, also next to a group separator
Control/Command+ANumberInputSelects all the text. Typing then replaces it and the mask starts over
Test: number-input.test.tsx › Control/Command+A selects all the text
EnterNumberInput in a <form>Submits the form with the number as shown. Native, never prevented
Test: number-input.test.tsx › Enter in a form submits it with the shown value (native)
EscapeNumberInputDoes nothing: the value and the focus stay
Test: number-input.test.tsx › Escape does nothing: the value and the focus stay
No keyits Field.LabelA click on the label focuses the input (native <label for>)
Test: number-input.test.tsx › clicking the label focuses the input

Copy, cut and undo (Control/Command+C, X and Z) are native too, and a dead key or IME composition is left alone until it ends (the mask's rows are in the TextInput contract). NumberInput adds no shortcuts.

Announcements#

NumberInput 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
A character is left out (a letter, a currency sign, a second decimal mark, a minus sign that isn't allowed)Only digits can be entered here.mask.characterNotAllowedPolite
A digit is left out because the number already has all its decimalsNo more decimals can be entered here.mask.maximumDecimalsPolite
A custom mask: a character is left outmask.*Polite

The text in all five languages

Change the text#

For your whole app, pass messages to KvirnProvider. For one NumberInput, 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 { NumberInput, useNumberInput } from '@kvirn-ui/react'

NumberInput

Renders <input type="text"> with the role textbox, never type="number" and never a spin button. It takes every attribute of an <input> except type, min and max, and passes ref to it. Put it in a Field: the label, help text and error are wired to it. The default theme is described on Theming.

PropTypeDefaultDescription
valuestring–Controlled: the number as shown, for example 1 250,50.
defaultValuestring–Uncontrolled: the native input keeps the value and a form submit sends it as shown.
onValueChange(value: string, details: TextInputChangeDetails) => void–Called on every change with the number as shown. details has reason, event, unmaskedValue (the machine form, -1234.5), isWithinRange, isComplete and rejected.
decimalsnumber0Digits after the decimal mark. With 0 no decimal mark is accepted.
allowNegativebooleanfalseAccepts a leading minus sign. The on-screen keyboard then shows text.
groupingbooleanfalseGroups the whole digits in threes with the page language’s separator.
minnumber–Lower limit. Reported as details.isWithinRange, never clamped and never a min attribute.
maxnumber–Upper limit. Reported as details.isWithinRange, never clamped and never a max attribute.
maskMaskInput | false–Replaces the number mask. false: a plain numeric text box that leaves nothing out and reports no mask details. A name, a pattern or a finished mask shapes the value instead.
announceRejectionsbooleantrueAnnounces, politely and at most once every few seconds, when a character is left out. Needs a KvirnProvider.
messagesPartial<KvirnMessages['mask']>–Overrides the texts of the announcements for this input.
disabledbooleanfalseNative disabled. A disabled Field disables the input too.
Class or attributeValuesMeaning
kv-input, kv-input--numericalwaysThe part classes. kv-input--numeric uses tabular figures.
kv-input--width-2, -4, -6, -10, -20class you addA width that fits the answer. A width is a hint, never a limit.
type, spellcheck"text", "false"Always a text box, never type="number", and never a spinbutton.
inputmode"numeric", "decimal" or "text"The on-screen keyboard: numeric for whole numbers, decimal with decimals, text when negatives are allowed. Your own inputMode wins.
id, aria-describedbyin a FieldFrom the Field. aria-describedby lists the descriptions and help texts in DOM order, then the error, and your own ids after them.
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-focusedpresent or absentThe input has focus, however it got it.
data-focus-visiblepresent or absentThe input has keyboard focus.

useNumberInput

Options

PropTypeDefaultDescription
decimalsnumber0Digits after the decimal mark. With 0 no decimal mark is accepted.
allowNegativebooleanfalseAccepts a leading minus sign. The on-screen keyboard then shows text.
groupingbooleanfalseGroups the whole digits in threes with the page language’s separator.
minnumber–Lower limit. Reported as details.isWithinRange, never clamped and never a min attribute.
maxnumber–Upper limit. Reported as details.isWithinRange, never clamped and never a max attribute.
maskMaskInput | false–Replaces the number mask. false: a plain numeric text box that leaves nothing out and reports no mask details. A name, a pattern or a finished mask shapes the value instead.
disabledbooleanfalseNative disabled. A disabled Field disables the input too.
onValueChange(value: string, details: TextInputChangeDetails) => void–Called on every change with the number as shown. details has reason, event, unmaskedValue (the machine form, -1234.5), isWithinRange, isComplete and rejected.
announceRejectionsbooleantrueAnnounces, politely and at most once every few seconds, when a character is left out. Needs a KvirnProvider.
messagesPartial<KvirnMessages['mask']>–Overrides the texts of the announcements for this input.

Result

PropTypeDefaultDescription
inputPropsNumberInputPartProps–Spread on an <input>: classes, type, 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 mask={false}.
format(unmaskedValue: string) => string–Formats a stored number for display, in the page’s language.
unmask(value: string) => string–The machine form of a displayed number: 1 250,50 becomes 1250.50.
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.

Strings

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

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

NumberInput has no strings of its own. It announces the mask’s, and messages replaces them for one box.

mask.characterNotAllowed

Announced when a character is left out.

LanguageDefault text
SvenskaHär kan du bara skriva siffror.
SuomiTähän voi kirjoittaa vain numeroita.
Norsk bokmålHer kan du bare skrive sifre.
Norsk nynorskHer kan du berre skrive siffer.
EnglishOnly digits can be entered here.

mask.maximumDecimals

Announced when a digit is left out because the decimals are full.

LanguageDefault text
SvenskaDu kan inte skriva fler decimaler.
SuomiDesimaaleja ei voi kirjoittaa enempää.
Norsk bokmålDu kan ikke skrive flere desimaler.
Norsk nynorskDu kan ikkje skrive fleire desimalar.
EnglishNo more decimals can be entered here.

mask.maximumLength

Announced by a pattern or RegExp mask of your own when a character is left out because it is full. The number mask never uses it.

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#

  • Negative numbers use the text keypad. iOS's numeric and decimal keypads have no minus sign, so allowNegative asks for inputmode="text". The mask still leaves out letters.
  • No provider, no announcement. KvirnProvider is required for announcements.
  • Undo. When the mask rewrites the value (writes a group separator, leaves out a character), undo can't go back past that step. Accepted, as for TextInput masks.
  • min and max are not announced. They are reported to your code only. Say the range in the help text.
  • 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.
  • Right-to-left pages: a negative number. Number masks don't set dir="ltr", so in a right-to-left page the minus sign of a negative number may show on the right of the digits. Use dir="ltr" on the NumberInput if your page needs it.
  • A typed space is announced as not allowed when grouping is on. The mask writes the group separator itself, so a space the user types is left out and announced (by design; whether it is noise is a question for the AT run).

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/apassnumber-input.stories.tsx, every story, 4 themes
Markup and ARIA (roles, names, ids, states)passn/apassnumber-input.test.tsx › the label names it, the help text and the error describe it, and the state is on it; expectNoA11yViolations
Keyboard contract rows (Vitest browser)passn/apass10 rows, each names a test (number-input.test.tsx › Tab and Shift+Tab move focus to and from the input, in DOM order)
Focus order and managementpassn/apassnumber-input.test.tsx asserts focus (toHaveFocus); first rule: Tab and Shift+Tab move focus to and from the input, in DOM order
Display modes (forced colours, 320px reflow, text spacing, reduced motion)passn/apassthe four sweep projects (storybook-forced-colors, -reduced-motion, -reflow, -text-spacing), run in CI
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

Research questions for the assistive technology (AT) run: is a left-out character's message read once, after the echo, and not repeated while a key is held? Is a text box that takes digits understood as a number field by each screen reader, without the spinbutton role? Does inputmode="numeric" or "decimal" bring up the right keyboard with VoiceOver and TalkBack, and does text (negatives allowed) still make a minus sign reachable? Does Dragon dictate "one thousand two hundred and fifty" into the field without corruption?

What to check#

With a screen reader and the keyboard, try:

  • Tab in: the label and the help text are read.
  • Typing digits says nothing.
  • A letter leaves the text unchanged and "Only digits can be entered here." is said once, politely.
  • With decimals, a second decimal mark or a digit past the decimals says "No more decimals can be entered here."
  • ArrowUp and ArrowDown move the caret. The number does not change, and no spin button is announced.
  • Paste "1 250,50": it shows the way the page writes a number.
  • On a phone the numeric keypad shows. With negatives allowed the text keypad shows, and a minus sign can be reached.