---
title: "Campo numérico"
description: "Permite introducir un número como número (escrito en la forma de la configuración regional de la persona o cambiado por pasos con una tecla o un botón, mantenido dentro de unos límites y con su unidad al lado), como un campo de formulario completo, compuesto por un campo y una entrada numérica."
url: "https://tanrei.chnotchy.com/es/components/number-field/"
last_updated: 2026-10-23T21:17:12.000Z
---

# Campo numérico

> Permite introducir un número como número (escrito en la forma de la configuración regional de la persona o cambiado por pasos con una tecla o un botón, mantenido dentro de unos límites y con su unidad al lado), como un campo de formulario completo, compuesto por un campo y una entrada numérica.

## Descripción general

Usa un campo numérico para un número que el producto lee como número: una cantidad, un tamaño, un porcentaje, un importe. Las personas lo escriben en la forma de su configuración regional, o lo cambian por pasos con las teclas de flecha o con los dos botones que hay al final del campo. El campo se dibuja y se mide como el campo de texto de la misma variante y el mismo tamaño.

**Se compone de** un [campo](https://tanrei.chnotchy.com/es/components/field/) y una [entrada numérica](https://tanrei.chnotchy.com/es/components/number-input/). El campo es el marco: la etiqueta, la marca de obligatorio o de opcional, la ayuda y el error. La entrada numérica es el control: la caja, el número, su unidad y los dos botones de paso. El campo numérico no dibuja nada propio y no tiene ningún token: cada propiedad que tiene es una propiedad de uno de los dos, que recibe sin cambios.

Un campo numérico ya es un campo: nunca se pone dentro de un [campo](https://tanrei.chnotchy.com/es/components/field/). Donde la etiqueta está en otro lugar —junto a un control deslizante, en una celda de una tabla—, usa la [entrada numérica](https://tanrei.chnotchy.com/es/components/number-input/) sola.

Es un bloque tan ancho como el lugar en el que se pone, y su caja lo llena. No tiene ancho propio: para un campo más estrecho, dale un lugar más estrecho.

En la web es `<tanrei-number-field>`. Las demás plataformas todavía no lo han implementado.

### Uso

`value` es un número, o `null` mientras el campo no contiene ninguno. Cambia cuando la persona **confirma** (el foco sale del campo, pulsa Enter o da un paso), y no con cada pulsación de tecla. Mientras escribe, el texto es suyo: nada se rechaza, se reformatea, se ajusta a los límites ni se redondea. Entretanto, `input` lleva el número que representa el texto.

**Web**

```html
<form>
  <tanrei-number-field name="quantity" label="Cantidad" value="1" min="1" max="99"
    required required-text="Obligatorio" invalid-text="Introduce un número." increment-label="Aumentar" decrement-label="Reducir"></tanrei-number-field>
</form>

<!-- Una unidad, un paso de un cuarto y sin límite superior. -->
<tanrei-number-field id="radius" label="Radio de esquina" value="8" min="0" step="0.25" suffix-text="px" increment-label="Aumentar" decrement-label="Reducir"></tanrei-number-field>

<!-- Dinero: un signo delante, un código detrás y siempre dos decimales. -->
<tanrei-number-field label="Importe" value="120" prefix-text="$" suffix-text="USD"
  min-fraction-digits="2" max-fraction-digits="2" increment-label="Aumentar" decrement-label="Reducir"></tanrei-number-field>

<script type="module">
  import '@tanrei/web/components/number-field';

  const radius = document.querySelector('#radius');
  // Una confirmación cambió el valor. Ya es el nuevo: un número, o null.
  radius.addEventListener('change', () => save(radius.value));
  // La persona está escribiendo o dando pasos: el número que representa el texto, sin ajustar a los límites y sin redondear, o null.
  radius.addEventListener('input', (e) => preview(e.detail.value));
  // Se confirmó un texto que no es un número. El campo lo conserva y muestra invalidText:
  // detail.text es ese texto, vacío donde el campo no recibió ninguno.
  radius.addEventListener('entryerror', (e) => console.log(e.detail.reason, e.detail.text));
</script>
```

**React**

```tsx
import { NumberField } from '@tanrei/react';

<NumberField label="Radio de esquina" value={radius} min={0} step={0.25} suffixText="px"
  incrementLabel="Aumentar" decrementLabel="Reducir"
  onChange={(event) => setRadius(event.currentTarget.value)} />
```

### Un nivel más abajo

El mismo campo, escrito a mano a partir de sus dos miembros, da la misma imagen y es, para la tecnología de apoyo, el mismo botón de número (spin button) con el mismo nombre, la misma descripción y los mismos estados:

```html
<tanrei-field label="Cantidad" required required-text="Obligatorio"
  supporting-text="Hasta 99 por pedido.">
  <tanrei-number-input name="quantity" min="1" max="99" invalid-text="Introduce un número."
    increment-label="Aumentar" decrement-label="Reducir"></tanrei-number-input>
</tanrei-field>
```

Baja a ese nivel cuando necesites una organización que el campo numérico no ofrece:

| Necesitas | Usa |
| --- | --- |
| Una etiqueta, la caja, una ayuda y un error | El campo numérico |
| Algo tuyo dentro del marco, junto a la caja o debajo de ella | Un [campo](https://tanrei.chnotchy.com/es/components/field/) con una [entrada numérica](https://tanrei.chnotchy.com/es/components/number-input/) y tu propio elemento dentro |
| La caja sola, bajo una etiqueta que está en otro lugar: junto a un control deslizante, una celda de una tabla, una barra de herramientas | La [entrada numérica](https://tanrei.chnotchy.com/es/components/number-input/) sola, que recibe su nombre de su propio `label` |

Lo que cambia un nivel más abajo es dónde se dice cada cosa. `name`, `value`, los límites y la unidad están en la entrada numérica, que es entonces el control con el que trata el formulario, y sus eventos se oyen en ella. `label`, `error`, `disabled` y la obligatoriedad se quedan en el campo, que se los pasa al control: no definas los de la propia entrada. No hay nada que el campo numérico haga y que no hagan el campo y la entrada numérica escritos a mano.

## Especificaciones

### El campo

| Parte | Qué es |
| --- | --- |
| Etiqueta | Del campo: encima del contenedor (`stacked`). En `filled` y `outlined` la dibuja la entrada numérica, flotando dentro de la caja, y el campo no dibuja fila de etiqueta. Es el nombre accesible, tanto si se dibuja como si se oculta con `labelHidden` |
| Marca de obligatoriedad | Del campo, después de la etiqueta: el tag de obligatoriedad en su forma de obligatorio, un asterisco o nada con `required`; el tag de obligatoriedad en su forma de opcional con `optional`. Una etiqueta flotante lleva el asterisco |
| Entrada | De la entrada numérica: el número como texto. Mientras la persona edita, lo que ha escrito; en los demás casos, el número confirmado en la forma de la configuración regional. Una sola línea, que se desplaza |
| Prefijo, sufijo | De la entrada numérica: texto fijo antes y después del número, como un signo de moneda o una unidad. Forman parte de la caja, nunca del valor |
| Botones de paso | De la entrada numérica: dos botones al final; el primero da un paso hacia abajo y el segundo, hacia arriba. Quítalos con `steppers` en false |
| Texto de apoyo | Del campo: una línea de ayuda. Mientras el campo está en error, el texto de error ocupa su lugar (o va debajo de ella, donde el sistema de diseño conserva las dos), y es `errorText` mientras `error` es true e `invalidText` mientras el texto no es un número. Empieza y termina en el margen interior del texto de la caja, con botones de paso y sin ellos |

Las tres variantes y los tres tamaños, `small` (32), `medium` (40) y `large` (56), son los del campo de texto. El sistema predeterminado solo incluye `stacked`.

El campo numérico no tiene ningún token propio. Su caja lee los [tokens de la entrada numérica](https://tanrei.chnotchy.com/es/components/number-input/#especificaciones), sus filas leen los [tokens del campo](https://tanrei.chnotchy.com/es/components/field/#especificaciones) y sus dos botones de paso, los [del botón](https://tanrei.chnotchy.com/es/components/button/#especificaciones), allí donde estén definidos. Para cambiar una sola instancia, define en ella el token de un miembro: `style="--tanrei-comp-field-label-gap: 0.75rem"`.

Los dos botones de paso son botones de la variante `text` y de tamaño mediano, uno al lado del otro. Con el sistema predeterminado ocupan 88 del ancho del campo, y cada uno es un objetivo táctil completo. Nunca se dibujan más pequeños ni apilados: donde una fila no tenga sitio para ellos, desactívalos. Las teclas siguen dando pasos.

### El valor y el texto

| Cuándo | Qué ocurre |
| --- | --- |
| La persona escribe, pega o dicta | No se cambia nada. `input` lleva el número que representa el texto, o `null` |
| El foco sale del campo, o Enter | El texto se confirma: se sube hasta `min`, se baja hasta `max`, se redondea a `maxFractionDigits`, pasa a ser el valor y se vuelve a escribir en la forma de la configuración regional. `change` se emite si el valor es distinto |
| El texto está vacío | El valor pasa a ser `null` |
| El texto no es un número | El texto se queda. El valor pasa a ser `null`, el campo queda en error y muestra `invalidText` —su `errorText` donde no hay ninguno—, y se emite `entryerror` |
| El producto define `value` | Se muestra el número, sea lo que sea lo que se haya escrito. No se emite ningún evento, y `min` y `max` no corrigen el número |

Un número confirmado se escribe con los dígitos y el separador decimal de la configuración regional, con entre `minFractionDigits` y `maxFractionDigits` dígitos después de este y sin separadores de agrupación, de modo que lo que se muestra se puede volver a escribir tal cual.

Un texto se lee con tolerancia, según el `locale` del campo o, donde este está vacío, según el idioma de la página:

- Los espacios alrededor del número y dentro de él se ignoran.
- Un guion, un signo menos o un signo más delante de los dígitos es el signo.
- Los dígitos ASCII, los dígitos propios de la configuración regional y los dígitos de ancho completo son todos dígitos.
- El separador de agrupación de la configuración regional se ignora entre dígitos: `1,234.50` se lee como 1234.5 en inglés.
- Un prefijo y un sufijo escritos o pegados se ignoran: `12 px` se lee como 12.
- Las letras, un exponente, dos separadores o un signo solo no son un número.

El campo nunca adivina entre dos configuraciones regionales. En alemán, donde la coma es el separador decimal, `1.500` se lee como 1500 y `1.5` como 15.

Un número y su unidad son una sola pieza de escritura. El prefijo se escribe antes del número y el sufijo después, en la dirección de la escritura de la propia unidad, sea cual sea la dirección de la página. Así, «44 px», «$ 120 USD» y «40 %» se leen en una página en árabe o en hebreo igual que en una en inglés, y una unidad escrita en letras árabes o hebreas queda a la izquierda del número. Los botones de paso y la etiqueta siguen a la página. `align="end"` pone el número junto a su unidad: a la derecha para una unidad en letras o signos latinos, en las dos direcciones. Para un código de moneda latino a la izquierda del número, empieza el sufijo con una marca de derecha a izquierda (U+200F).

### Los pasos

| Entrada | Qué ocurre |
| --- | --- |
| Flecha arriba, Flecha abajo | Da un paso de `step` |
| Re Pág, Av Pág | Da un paso de diez veces `step` |
| Una pulsación en un botón de paso | Da un paso. Si se mantiene pulsado, se repite: al cabo de medio segundo, después diez veces por segundo y después veinte |
| Inicio, Fin, Flecha izquierda, Flecha derecha | Mueven el cursor de texto dentro del texto |
| La rueda del ratón, un arrastre | Nada. La página se desplaza |

Un paso lleva al siguiente número de la cuadrícula del paso, contada desde `min` (desde cero si no lo hay): con un paso de 5, desde 12 un paso hacia arriba lleva a 15 y uno hacia abajo, a 10. Se calcula en decimal, así que 0.2 más un paso de 0.1 es 0.3. Desde un campo vacío, un paso lleva al número más cercano a cero que permiten los límites.

`step` dice hasta dónde llega un paso. No limita lo que se puede escribir: con un paso de 5, un 12 escrito sigue siendo 12. Para aceptar solo algunos números, valida el valor y activa `error`.

### Con un control deslizante

Un número junto a un control deslizante, bajo un mismo título de fila, es la caja sola: una [entrada numérica](https://tanrei.chnotchy.com/es/components/number-input/#con-un-control-deslizante), que recibe su nombre de su propio `label`. Su página tiene el ejemplo.

- Category: Text inputs
- Level: composed
- Listing: default
- Built from: Field, Number input
- Page: https://tanrei.chnotchy.com/components/number-field/
- Spec: https://github.com/chnotchy/tanrei/blob/main/specs/number-field.spec.json

### Availability

| Design system | Has it | Notes |
| --- | --- | --- |
| Tanrei (`tanrei`) | Yes | Variants left out: `filled`, `outlined`. |
| Cupertino (Apple HIG-inspired) (`cupertino`) | Yes | — |
| M3 Expressive-like (Material 3 Expressive-inspired) (`m3-expressive-like`) | Yes | — |
| M3-like (Material 3-inspired) (`m3-like`) | Yes | — |

### Platforms

- Web: the element `<tanrei-number-field>`, registered by importing `@tanrei/web` (or only its own module, `@tanrei/web/components/number-field`).
- React: `NumberField` from `@tanrei/react`.

| Platform | Name | Status |
| --- | --- | --- |
| Web | `tanrei-number-field` | lagging |
| SwiftUI | `TanreiNumberField` | planned |
| Jetpack Compose | `TanreiNumberField` | planned |
| Flutter | `TanreiNumberField` | planned |
| React Native | `NumberField` | planned |

Names a platform gives in its own idiom:

| Spec | Web | SwiftUI | Jetpack Compose | Flutter | React Native |
| --- | --- | --- | --- | --- | --- |
| `label` (prop) | `label` | `label` | `label` | `labelText` | `label` |
| `labelHidden` (prop) | `labelHidden` | `labelsHidden` | `labelHidden` | `labelHidden` | `labelHidden` |
| `placeholder` (prop) | `placeholder` | `prompt` | `placeholder` | `hintText` | `placeholder` |
| `supportingText` (prop) | `supportingText` | `supportingText` | `supportingText` | `helperText` | `supportingText` |
| `error` (prop) | `error` | `error` | `isError` | `isError` | `error` |
| `disabled` (prop) | `disabled` | `disabled` | `enabled` | `enabled` | `disabled` |
| `required` (prop) | `required` | `isRequired` | `required` | `required` | `required` |
| `optional` (prop) | `optional` | `isOptional` | `optional` | `optional` | `optional` |
| `min` (prop) | `min` | `in` | `min` | `min` | `min` |
| `max` (prop) | `max` | `in` | `max` | `max` | `max` |
| `steppers` (prop) | `noSteppers` | `steppers` | `steppers` | `steppers` | `steppers` |
| `incrementLabel` (prop) | `incrementLabel` | `incrementLabel` | `incrementContentDescription` | `incrementSemanticLabel` | `incrementAccessibilityLabel` |
| `decrementLabel` (prop) | `decrementLabel` | `decrementLabel` | `decrementContentDescription` | `decrementSemanticLabel` | `decrementAccessibilityLabel` |
| `prefixText` (prop) | `prefixText` | `prefix` | `prefix` | `prefixText` | `prefix` |
| `suffixText` (prop) | `suffixText` | `suffix` | `suffix` | `suffixText` | `suffix` |
| `valueText` (prop) | `valueText` | `valueText` | `stateDescription` | `semanticValue` | `valueText` |
| `input` (event) | `input` | `onInput` | `onInput` | `onInput` | `onInput` |
| `change` (event) | `change` | `value` | `onValueChange` | `onChanged` | `onValueChange` |
| `action` (event) | `action` | `onSubmit` | `keyboardActions` | `onSubmitted` | `onSubmitEditing` |
| `entryError` (event) | `entryerror` | `onEntryError` | `onEntryError` | `onEntryError` | `onEntryError` |

Statuses: `planned` — In the inventory. Nothing shippable exists yet. `lagging` — An implementation of an earlier spec exists; it has not caught up with the current one. `alpha` — Implemented with tests. The API may still change. `beta` — Feature complete and at parity. Only fixes are expected. `stable` — Covered by semantic versioning. `deprecated` — Still shipped; scheduled for removal.

### Anatomy

- `field`: The Field: the label row with its glyph and its requirement mark, and the supporting row with the help and the error text. In a look whose input floats the label it draws no label row.
- `number-input`: The number input, as the Field's one control: the box, the number in it, the prefix and the suffix, the two steppers, and the label that floats in the box in the looks that float one.

### Props

| Prop | Type | Default | Web attribute | Description |
| --- | --- | --- | --- | --- |
| `variant` | `enum`: `stacked`, `filled`, `outlined` | `"stacked"` | `variant` | The text input's three looks, so that a number input is drawn as the text inputs beside it: stacked is a filled box that shows focus and error with a line inside its edge and draws no label — the label of the Field that frames it stands above it; filled and outlined float the label inside the box. Use one style per form. A design system may leave some out (the Tanrei system ships stacked only) or add values. (From Number input.) |
| `size` | `enum`: `small`, `medium`, `large` | `"medium"` | `size` | Minimum height of the container: stacked 32 / 40 / 56, as tall as a Button of the same size, so that the box and a Button side by side in one row stand as tall as each other; filled and outlined 40 / 48 / 56, which hold the label that floats inside them. These are the text input's three sizes, small for a bar, a toolbar or a dense row of controls. The hit area always meets the minimum target. A design system may add values. (From Number input.) |
| `value` | `number` | — | `value` | The committed number, or null (the platform's absent value) while the field holds none. It changes when the person commits — focus leaves, the action key, a step — not on every keystroke; input carries what is being typed. (From Number input.) |
| `label` | `string` | `""` | `label` | Names the control, visibly and to assistive technology. Required, unless the control names itself (a checkbox or a switch with its own label): then leave it empty and the field adds only help and an error. (From Field: Names the number input. In a filled or outlined look the input draws it, floating in its box, and the Field draws no label row (FLD-25, NMI-8).) |
| `labelHidden` | `boolean` | `false` | `label-hidden` | Does not draw the label, which stays the accessible name. For a control whose visible label is elsewhere (a table column, a toolbar). (From Field: Hides the label wherever it would be drawn: the Field's row, or the input's floating label (FLD-25). Where no message is shown either, the bare number input, named by its own label, is that control without a frame.) |
| `placeholder` | `string` | `""` | `placeholder` | A hint shown while the input is empty and the label is not in the input line. Never a replacement for a name. (From Number input.) |
| `supportingText` | `string` | `""` | `supporting-text` | Help shown below the control and given to assistive technology as the control's description. While the field is in error it gives way to errorText, unless the design system keeps both (comp.field.error-text.placement append). (From Field.) |
| `errorText` | `string` | `""` | `error-text` | Shown while error is true, in supportingText's place — or below it, which then stays, where the design system's comp.field.error-text.placement is append: what is wrong and how to put it right, in words. (From Field.) |
| `error` | `boolean` | `false` | `error` | Puts the field in the error condition: the error text is drawn, the control is exposed as invalid and, where it has an error condition of its own, drawn in it. What a value means is the product's to validate; the field never sets this itself. (From Field: The Field puts its number input in the input's own error condition (FLD-8, NMI-10); the steppers stay as they are.) |
| `disabled` | `boolean` | `false` | `disabled` | Disables the control and draws the frame as disabled. Disable a framed control here, not on the control, so that its label follows. (From Field: The Field disables its number input, and with it both steppers (FLD-14, NMI-32); the number field is then left out of its form (NUM-48).) |
| `readOnly` | `boolean` | `false` | `readonly` | The number can be focused, selected and copied, but not changed: no key steps it and no stepper is drawn. (From Number input.) |
| `required` | `boolean` | `false` | `required` | What the form asks of the control: true exposes it as required and draws the required mark beside the label. It never validates: a missing answer is the product's to report with error. (From Field: The Field exposes its number input as required (FLD-10, NMI-12).) |
| `optional` | `boolean` | `false` | `optional` | Draws the optional tag after the label and adds optionalText to the control's description, because assistive technology has no state for it. Ignored while required is true: a control is never both. (From Field.) |
| `requiredMark` | `enum`: `auto`, `tag`, `asterisk`, `none` | `"auto"` | `required-mark` | How this control shows that it is required: tag is a small filled Tag with requiredText, asterisk is "*" after the label, none draws nothing and keeps the semantics. Auto takes comp.field.requirement.mark, which follows sys.behavior.requirement-mark, the system's one answer. Ignored unless required is true. (From Field.) |
| `requiredText` | `string` | `""` | `required-text` | The text of the required tag, in the product's language ("Required", "必須"). The product's: Tanrei has no word for it. Empty reads the product's words; with neither, FLD-24 says what is drawn. (From Field.) |
| `optionalText` | `string` | `""` | `optional-text` | The text of the optional tag, in the product's language ("Optional", "任意"); also read to assistive technology as part of the description. The product's: Tanrei has no word for it. Empty reads the product's words. (From Field.) |
| `min` | `number` | — | `min` | The lowest number a commit keeps; a lower one is raised to it. Null for no limit. It is also where the steps are counted from. (From Number input.) |
| `max` | `number` | — | `max` | The highest number a commit keeps; a higher one is lowered to it. Null for no limit. (From Number input.) |
| `step` | `number` | `1` | `step` | How far Up Arrow, Down Arrow and a stepper move the number; Page Up and Page Down move ten times as far. It does not limit what may be typed. (From Number input.) |
| `steppers` | `boolean` | `true` | — | Draws the two stepper buttons at the end of the field. False for a field in a row too narrow for them, or beside a slider that does their work; the keys still step. (From Number input.) |
| `incrementLabel` | `string` | `""` | `increment-label` | The accessible name of the stepper that steps up, in the product's language ("Increase"). The product's: Tanrei has no word for it. Empty reads the product's words. Required while the steppers are shown. (From Number input.) |
| `decrementLabel` | `string` | `""` | `decrement-label` | The accessible name of the stepper that steps down, in the product's language ("Decrease"). The product's: Tanrei has no word for it. Empty reads the product's words. Required while the steppers are shown. (From Number input.) |
| `prefixText` | `string` | `""` | `prefix-text` | Fixed text before the number, not part of the value: a currency sign ("$", "¥"). (From Number input.) |
| `suffixText` | `string` | `""` | `suffix-text` | Fixed text after the number, not part of the value: the unit ("px", "ms", "%", "kg"). Read to assistive technology with the number. (From Number input.) |
| `valueText` | `string` | `""` | `value-text` | The value as words ("12 pixels", "3 stars"), given to assistive technology in place of the number with its prefix and suffix. The same text a Slider beside the field takes as its valueText. (From Number input.) |
| `align` | `enum`: `start`, `end` | `"start"` | `align` | Where the number stands in the input: at the start, as the text of every other field, or at the end, for a number in a column of numbers whose digits should line up. (From Number input.) |
| `minFractionDigits` | `number` | `0` | `min-fraction-digits` | The fewest digits shown after the decimal separator; zeros fill them (2 for an amount of money: "12.00"). (From Number input.) |
| `maxFractionDigits` | `number` | `3` | `max-fraction-digits` | The most digits kept after the decimal separator: a commit rounds to it. 0 makes the field hold whole numbers and asks for a keyboard without a separator. (From Number input.) |
| `locale` | `string` | `""` | `locale` | A BCP 47 language tag ("en-US", "de-DE", "ar-EG") for how the number is shown and read: its digits and its decimal separator. Empty uses the platform's current locale. The value itself is a number in every locale. (From Number input.) |
| `invalidText` | `string` | `""` | `invalid-text` | The words for an input committed with a text that is not a number ("Enter a number"): given to the Field that frames it, which shows them as its error text and, while they are empty, shows its own errorText (NMI-21, FLD-28). (From Number input: Shown by the Field, in its supporting row (FLD-28).) |

### Events

| Event | Description |
| --- | --- |
| `input` | The person changed the text, or a step changed the value; carries the number the text reads as — not clamped, not rounded — or the empty value while it reads as none. Emitted for every change, not when the product sets value. What a Slider beside the field follows. (From Number input.) |
| `change` | A commit changed the value: focus left the field, the action key was pressed, a key or a stepper stepped it, or a held stepper was released; carries the value. (From Number input.) |
| `action` | The person pressed the keyboard's action key (Enter, Return, Done). (From Number input.) |
| `entryError` | The person committed a text that is not a number; carries the reason (invalid) and invalidText, the words the input has for it. The entry error itself is shown by the Field that frames the input (NMI-21). (From Number input.) |

### Slots

| Slot | Description |
| --- | --- |
| `label-icon` | A glyph before the label. (From Field.) |

### States

`enabled`, `disabled`, `hovered`, `focused`, `error`

### Accessibility

- Role: `spinbutton`
- Labeling: The number field adds nothing to what its members expose and coordinates nothing: the Field gives the number input its name, its description and its required, invalid and disabled states (FLD-8, FLD-10, FLD-11, FLD-14), and the number input carries them on its own element with its value, its limits and its value text (NMI-12, NMI-34). Assistive technology meets one spin button named by label and two buttons that are no focus stops, exactly as it meets a Field around a number input written by hand.
- Minimum target size: yes

| Keys | Action |
| --- | --- |
| Every key | The number input's (its accessibility block; NMI-20, NMI-23). The number field handles no key and adds no focus stop (NUM-49). |

- One level down is the same thing: a Field with a number input in it. Every fixture has that pair as its twin, and the accessibility tree of the two is the same (NUM-47).
- On the web the two members stand in the number field's own shadow root, so the form meets the number field and not the input (NUM-48); focus passes through to the input (NUM-49).
- Two levels down, for a number whose label is elsewhere and that shows no message, is the number input alone, named by its own label: beside a slider under one row title, in a table, in a toolbar.

### Behaviour

Requirements in EARS form, each with its stable id.

- **NUM-47** THE number field SHALL be a Field that frames one number input, and nothing else. It SHALL give label, labelHidden, supportingText, errorText, error, disabled, required, optional, requiredMark, requiredText and optionalText to its Field and every other prop to its number input, each unchanged; SHALL hold the label-icon slot for its Field; and SHALL emit its number input's events as its own, each once. THE number field SHALL be as wide as the place it stands in, and its number input SHALL fill it: it is a block with no width of its own, as its Field is (FLD-1), around a control that fills the width it is given (NMI-36). It SHALL draw no part of its own, hold no state of its own and have no token of its own: what it shows, how it behaves and what it exposes to assistive technology SHALL be exactly what that Field and that number input do when a product places the one in the other (FLD-1 to FLD-28; NMI-1 to NMI-46) — the label row and its requirement mark (FLD-2 to FLD-6), or the label that floats in the box with the Field's row left out (FLD-25, NMI-7, NMI-8); the supporting row and the error (FLD-7 to FLD-9, FLD-26); the name, the description and the states (FLD-10, FLD-11, FLD-14, NMI-12, NMI-32); a text that is not a number shown as an error in the Field's row, in the input's words (FLD-28, NMI-21); and the two steppers, which are the number input's Buttons and stand inside its box (NMI-25).
- **NUM-48** WHERE the platform has forms (the web) THE number field SHALL be the one control the form sees: it SHALL take name, submit its number input's value as that input submits it — a decimal number with ASCII digits and a period, or an empty string WHILE it holds none (NMI-35) — reset to the value it was first given, restore it on navigation, report to the form's constraint validation exactly what its number input would report there (a missing value WHILE required is true and it holds none, NMI-12; a bad input WHILE an entry error lasts, NMI-21), and be left out WHILE disabled is true or a disabled group of the form holds it; its number input and its Field SHALL take no part in the form themselves. WHEN the action key asks for the form's submission (NMI-20) the form asked SHALL be the number field's own.
- **NUM-49** WHEN the number field is given focus — by the product, by a press on any part of it that FLD-12 or NMI-14 gives to the input, or by a form that reports its validity — THE number field SHALL pass the focus to its number input and SHALL add no stop to the focus order: it has one stop, its input, and the steppers are none (NMI-25). A press on a stepper SHALL step and move no focus, in the number field as in the bare input (NMI-26). WHILE focus is inside it THE number field SHALL count as focused for its Field (FLD-13).
- **NUM-50** IF the number field is placed in a Field THE number field SHALL in debug builds report that it is a field already and that the bare control is the number input, and both SHALL still render (FLD-15). WHILE it stands in a field group THE number field SHALL follow that group's disabled, through its own Field, and take nothing else from the group (FGR-14).
- **NUM-51** THE number field SHALL have no words of its own and SHALL read none: requiredText and optionalText are read by its Field (FLD-24), incrementLabel and decrementLabel by its number input (NMI-44), each from the instance's prop and then from the product's words.
- **NUM-52** WHERE the platform has ARIA attributes (the web), WHEN the product sets an aria- attribute on the host, by the attribute or by the ARIA property that reflects it, THE number field SHALL move it to the data-aria- attribute of the same name, so that the host is no second node with its name, description or state, and SHALL expose it on the element that carries its role — an id reference by the elements it names in the host's tree or a tree around it, an error message as part of the description while the number field is invalid — except those the number field owns (aria-label, aria-labelledby, aria-disabled), which it SHALL move and not expose: its name is label (NUM-47). WHEN the product removes the aria- attribute or its data-aria- twin, or sets the ARIA property that reflects it (ariaLabel, ariaDescribedByElements…) to null, THE number field SHALL take it off that element. WHEN the product sets an aria- attribute the number field owns THE number field SHALL report it in debug builds.

### Tokens

As written in the token documents (DTCG): an alias in braces names the token it takes its value from, which each design system resolves. On the web each token is a CSS custom property: `--tanrei` and the name after `tanrei`, joined by hyphens (`tanrei.comp.field.…` → `--tanrei-comp-field-…`).

#### `tanrei.comp.field`

| Token | Type | Value |
| --- | --- | --- |
| `comp.field.label.typescale` | `typography` | `{tanrei.sys.typescale.label}` |
| `comp.field.label.gap` | `dimension` | `{tanrei.sys.space.space100}` |
| `comp.field.label-icon.size` | `dimension` | `{tanrei.sys.icon.small}` |
| `comp.field.label-icon.gap` | `dimension` | `{tanrei.sys.space.space100}` |
| `comp.field.requirement.mark` | `number` | `{tanrei.sys.behavior.requirement-mark}` |
| `comp.field.requirement.gap` | `dimension` | `{tanrei.sys.space.space100}` |
| `comp.field.requirement.asterisk-gap` | `dimension` | `{tanrei.sys.space.space25}` |
| `comp.field.supporting-text.typescale` | `typography` | `{tanrei.sys.typescale.label-small}` |
| `comp.field.supporting-text.gap` | `dimension` | `{tanrei.sys.space.space50}` |
| `comp.field.counter.gap` | `dimension` | `{tanrei.sys.space.space200}` |
| `comp.field.motion.state-duration` | `duration` | `{tanrei.sys.motion.role.state.default}` |
| `comp.field.motion.state-easing` | `cubicBezier` | `{tanrei.sys.motion.easing.state}` |
| `comp.field.standard.label.color` | `color` | `{tanrei.sys.color.on-surface}` |
| `comp.field.standard.label-icon.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.supporting-text.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.counter.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.required-asterisk.color` | `color` | `{tanrei.sys.color.primary}` |
| `comp.field.standard.error.label.color` | `color` | `{tanrei.sys.color.on-surface}` |
| `comp.field.standard.error.label-icon.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.error.supporting-text.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.error.counter.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.error.required-asterisk.color` | `color` | `{tanrei.sys.color.primary}` |
| `comp.field.standard.error.value-text.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.value-text.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.error-text.color` | `color` | `{tanrei.sys.color.error}` |
| `comp.field.value-text.typescale` | `typography` | `{tanrei.sys.typescale.label}` |
| `comp.field.value-text.gap` | `dimension` | `{tanrei.sys.space.space200}` |
| `comp.field.error-text.gap` | `dimension` | `{tanrei.sys.space.space50}` |
| `comp.field.error-text.placement` | `number` | `0` |

Per-state tokens, valued by the design system's pattern rules (not written by hand):

- `comp.field.<variant>.<state>.<property>` for the variants `standard`, the states `focused`, `disabled` and the properties `label.color`, `label-icon.color`, `supporting-text.color`, `required-asterisk.color`, `error.label.color`, `error.label-icon.color`, `error.supporting-text.color`, `error.required-asterisk.color`, `counter.color`, `error.counter.color`, `value-text.color`, `error.value-text.color`, `error-text.color`.

### Qué dibuja la web de otra manera

- El shadow root del elemento contiene un `<tanrei-field>` con un `<tanrei-number-input>` dentro. Importar el campo numérico define ambos.
- El campo numérico es un elemento asociado a formularios, y el único control con el que trata su formulario. Recibe `name` y envía su valor como un número decimal simple (`12.5`), muestre lo que muestre la configuración regional. Se restablece al valor del atributo `value`, y notifica al formulario que falta un valor mientras `required` y no contiene ninguno, y que la entrada es incorrecta mientras su texto no es un número.
- Es un bloque tan ancho como su lugar. En un lugar que no da ningún ancho, una etiqueta larga lo hace más ancho que su caja: dale ahí un ancho.
- Las partes son las de los miembros, con sus propios nombres: `label`, `label-icon`, `requirement-label` y `supporting-text` del campo; `container`, `outline`, `active-indicator`, `input`, `prefix`, `suffix` y `stepper` de la entrada numérica. `label` y `requirement-label` llegan a la de los dos que se dibuje; `field-label` y `number-input-label` llegan a una sola. Los dos miembros son las partes `field` y `number-input`.
- El `detail.text` de `entryerror` es el `invalidText` de la entrada, vacío donde no se dio ninguno. Los tipos del detalle son los de la entrada numérica: `TanreiNumberInputInputDetail` y `TanreiNumberInputEntryErrorDetail`.
- `steppers` es el atributo inverso `no-steppers`, y `readOnly` es `readonly`.
- `input` es un CustomEvent con `detail.value`. `change` y `action` son eventos simples: lee `value` del elemento. Salvo que `action` se cancele, a continuación se pide al formulario que se envíe.
- Sin `locale`, el campo lee el atributo `lang` más cercano y, después, el idioma del navegador.
- Además del separador de la configuración regional, un punto se lee como separador decimal siempre que la configuración regional no agrupe con puntos.
- Una tecla de página da diez pasos sobre la cuadrícula del propio paso, como la de un deslizador: con un paso de 2, Re Pág desde 42 da 62, y luego 82.
- En iOS y iPadOS, el campo pide el teclado completo mientras se pueda escribir un número negativo, porque allí el teclado decimal no tiene signo menos.
- Antes de que el elemento esté definido, no tiene tamaño. Reserva la altura.

## Pautas

### Campo numérico, campo de texto o control deslizante

| Aspecto | Campo numérico | Campo de texto | Control deslizante |
| --- | --- | --- | --- |
| Contiene | Un número | Cualquier texto | Un número dentro de un intervalo |
| Se elige | Escribiendo o dando pasos | Escribiendo | Arrastrando |
| Va bien para | Un valor que se conoce | Dígitos que no son una cantidad | Un valor que se elige a ojo |

Un código postal, un número de tarjeta, un número de teléfono y un código de un solo uso son dígitos, pero no cantidades: nadie le suma uno a un código postal. Usa para ellos un [campo de texto](https://tanrei.chnotchy.com/es/components/text-field/).

### Recomendado

- Escribe una etiqueta que nombre lo que se cuenta, y mantenla visible en un formulario.
- Pon la unidad en `suffixText` y un signo de moneda en `prefixText`.
- Da un `valueText` donde el sufijo se leería mal: «1,5 veces» para `×`.
- Escribe `invalidText` de modo que diga qué hay que escribir: «Introduce un número.»
- Define `maxFractionDigits` en 0 para los números enteros. El teclado no tiene entonces separador.
- Da `incrementLabel` y `decrementLabel`, en el campo o una sola vez para todo el producto con `setWords()`. Tanrei no incluye textos propios: un botón de paso sin nombre se dibuja igualmente y sigue dando pasos con un puntero, y queda oculto para la tecnología de apoyo, donde el botón de número da los pasos por sí mismo.

### Evita

- No uses un campo numérico para dígitos que no son una cantidad.
- No guardes con `input`. Se emite con cada pulsación de tecla; `change` lleva el valor confirmado.
- No esperes que `min` y `max` corrijan un valor que defines tú. Se aplican a lo que la persona confirma.
- No pongas dentro del campo un control para elegir la unidad. Pon un [select](https://tanrei.chnotchy.com/es/components/select/) a su lado.
- No pongas un campo numérico dentro de un campo. Ya es un campo; el control que un campo enmarca es la [entrada numérica](https://tanrei.chnotchy.com/es/components/number-input/).
- No ocultes la etiqueta de un campo numérico para poner la caja bajo una etiqueta tuya. Usa la entrada numérica.

## Accesibilidad

### De qué se encarga el componente

- La entrada es un botón de número (spin button). Su nombre es `label`, tanto si se dibuja como si se oculta, y nunca el marcador de posición.
- Su valor es el número confirmado, y sus límites son `min` y `max`.
- El texto de apoyo o de error que se muestra es su descripción, con `optionalText` mientras el campo es opcional.
- Se expone como no válido mientras `error` es true o su texto no es un número, como obligatorio mientras `required` está activado, y como de solo lectura.
- Un error que aparece mientras el campo tiene el foco se anuncia una vez, de forma cortés; también un texto que no es un número.
- Los botones de paso son botones que reciben su nombre de `decrementLabel` y de `incrementLabel`; uno al que nadie dio nombre queda oculto para la tecnología de apoyo. Están fuera del orden del foco, porque las teclas de flecha dan los pasos desde la entrada; quien explora la pantalla con el tacto los encuentra igualmente.
- Una pulsación en un botón de paso no mueve el foco, así que no hace aparecer el teclado en pantalla.
- Mientras un método de entrada está componiendo, el campo no lee nada y no gestiona ninguna tecla.
- La rueda del ratón nunca cambia el número.
- El área de pulsación del campo cumple el objetivo mínimo, y cada botón de paso es un objetivo completo.
- Con el texto al 200%, la etiqueta y la ayuda saltan de línea. El número se queda en una sola línea, y se desplaza.
- Donde la fila no puede contener el número y los botones de paso uno al lado del otro —con el texto al 200% en una ventana estrecha, con un prefijo y un sufijo largo—, los botones de paso pasan a una fila propia debajo del número, al final de la caja. Nunca se ocultan, porque en una pantalla táctil son la única forma de dar pasos.
- Con colores forzados, el campo gana un borde, y un error se distingue por sus palabras y por el estado no válido.
- En un diseño de derecha a izquierda, los botones de paso y la etiqueta se reflejan: los botones de paso quedan en el extremo izquierdo. El número y su unidad se escriben como los escribe la escritura de la propia unidad: una unidad en letras o signos latinos después del número, de izquierda a derecha, y una unidad en la escritura de la página a la izquierda del número. Lo que se lee en voz alta no cambia.

Carencias conocidas en la web:

- Chromium lee el número sin su unidad: obtiene el texto del valor a partir del texto que hay en la entrada, y pasa por alto el que indica el campo. Nombra la unidad en la etiqueta donde importe.
- Antes de que el elemento esté definido, no se dibuja nada.

### Qué debes hacer tú

- Da un `label` a cada campo numérico.
- Escribe `invalidText` en el campo. Da `requiredText`, `optionalText`, `incrementLabel` y `decrementLabel` en el campo, o una sola vez para todo el producto con `setWords()`. Tanrei no incluye textos propios; si falta uno, se notifica en desarrollo. Consulta [Los textos del producto](https://tanrei.chnotchy.com/es/foundations/words/).
- Valida tú el valor, activa `error` y escribe `errorText` de modo que diga cómo corregir el número.
- Da el mismo nombre a un control deslizante y a la entrada numérica que tiene al lado.
