Primitiveinput

OTP Field

Stable

Código de uso único, um caractere por casa. Composto sobre Base UI OTP Field, que avança o foco ao digitar, volta com Backspace, preenche todas as casas ao colar e marca a primeira casa com autocomplete="one-time-code", para o código de um SMS entrar num toque. Cada casa usa a borda, o anel de foco e o estado inválido do Input, e o OTPFieldSeparator compõe o Separator entre grupos. Use para códigos de verificação, autenticação em dois fatores e PINs curtos de tamanho fixo; para qualquer outro texto use Input.

Instalação

npx up-web-ds add otp-field

Preview

Basic

With Description

Enviamos um código de 6 dígitos para w•••@upweb.studio.

With Separator

Abra o autenticador e digite o código de 6 dígitos.

Large

Fornecido pelo aplicador no início da sessão.

Masked

Os 4 dígitos escolhidos no primeiro acesso.

Alphanumeric

Letras e números, como no e-mail de convite.

Disabled

Aguarde 45 s para pedir um novo código.

Invalid

Código expirado. Peça um novo código e tente de novo.

On Complete

0 de 6 dígitos.

All states

Basic

With Description

Enviamos um código de 6 dígitos para w•••@upweb.studio.

With Separator

Abra o autenticador e digite o código de 6 dígitos.

Large

Fornecido pelo aplicador no início da sessão.

Masked

Os 4 dígitos escolhidos no primeiro acesso.

Alphanumeric

Letras e números, como no e-mail de convite.

Disabled

Aguarde 45 s para pedir um novo código.

Invalid

Código expirado. Peça um novo código e tente de novo.

On Complete

0 de 6 dígitos.

Usage

Imports de OTP Field
import { Label } from '@/components/ui/label'
import { OTPField, OTPFieldInput } from '@/components/ui/otp-field'
import { useId } from 'react'
OTP Field
function VerificationCode() {
  const id = useId()

  return (
    <div className="flex flex-col gap-2">
      <Label htmlFor={id}>Código de verificação</Label>
      <OTPField id={id} length={6}>
        {SIX.map((digit) => (
          <OTPFieldInput key={digit} aria-label={`Dígito ${digit} de 6`} />
        ))}
      </OTPField>
    </div>
  )
}

Props

OTPField

Props de OTPField
PropTypeDefaultDescription
size"default" | "lg"'default'Size of each slot. `default` is the height of `Input`; `lg` is one step up, for a code that is the only thing on the screen.
length, obrigatórianumbersem valor padrãoThe number of OTP input slots. Required so the root can clamp values, detect completion, and generate consistent validation markup before all slots hydrate.
autoCompletestring'one-time-code'The input autocomplete attribute. Applied to the first slot and hidden validation input.
autoSubmitbooleanfalseWhether to submit the owning form when the OTP becomes complete.
classNamestring | ((state: OTPFieldRootState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
defaultValuestringsem valor padrãoThe uncontrolled OTP value when the component is initially rendered.
disabledbooleanfalseWhether the component should ignore user interaction.
formstringsem valor padrãoA string specifying the `form` element with which the hidden input is associated. This string's value must match the id of a `form` element in the same document.
idstringsem valor padrãoThe id of the first input element. Subsequent inputs derive their ids from it (`{id}-2`, `{id}-3`, and so on).
inputMode"search" | "text" | "none" | "tel" | "url" | "email" | "numeric" | "decimal"sem valor padrãoThe virtual keyboard hint applied to the slot inputs and hidden validation input. Built-in validation modes provide sensible defaults, but you can override them when needed.
maskbooleanfalseWhether the slot inputs should mask entered characters. Pass `type` directly to individual `<OTPField.Input>` parts to use a custom input type.
namestringsem valor padrãoIdentifies the field when a form is submitted.
normalizeValue((value: string) => string)sem valor padrãoFunction that normalizes the OTP value after whitespace and `validationType` filtering. It runs whenever OTP Field normalizes a value, including initial/default values, controlled values, and user edits. The returned value is filtered by `validationType` again, then clamped to `length`. It should be idempotent because OTP Field may normalize the same value more than once while handling edits, storing state, and rendering controlled or uncontrolled values. Non-idempotent normalizers can compound across those normalization passes. Characters rejected while normalizing typed or pasted text are reported through `onValueInvalid`.
onValueChange((value: string, eventDetails: OTPFieldRoot.ChangeEventDetails) => void)sem valor padrãoCallback fired when the OTP value changes. The `eventDetails.reason` indicates what triggered the change: - `'input-change'` for typing or autofill - `'input-clear'` when a character is removed by text input - `'input-paste'` for paste interactions - `'keyboard'` for keyboard interactions that change the value
onValueComplete((value: string, eventDetails: OTPFieldRoot.CompleteEventDetails) => void)sem valor padrãoCallback function that is fired when the OTP value becomes complete, or when a complete value is pasted while the OTP is already complete. When the value changes, it runs later than `onValueChange`, after the internal value update is applied. If a complete pasted value matches the current value, `onValueChange` does not fire. If `autoSubmit` is enabled, it runs immediately before the owning form is submitted.
onValueInvalid((value: string, eventDetails: OTPFieldRoot.InvalidEventDetails) => void)sem valor padrãoCallback fired when entered text contains characters that are rejected by validation or normalization before the OTP value updates. The `value` argument is the attempted user-entered string before normalization.
readOnlybooleanfalseWhether the user should be unable to change the field value.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, OTPFieldRootState>sem valor padrãoAllows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.
requiredbooleanfalseWhether the user must enter a value before submitting a form.
styleReact.CSSProperties | ((state: OTPFieldRootState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.
validationTypeOTPValidationType'numeric'The type of input validation to apply to the OTP value.
valuestringsem valor padrãoThe OTP value.

Estende React.ComponentProps< typeof OTPFieldPrimitive.Root >. Aceita também os atributos padrão de um elemento React (272 não listados).

OTPFieldInput

Props de OTPFieldInput
PropTypeDefaultDescription
classNamestring | ((state: OTPFieldInputState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, OTPFieldInputState>sem valor padrãoAllows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.
styleReact.CSSProperties | ((state: OTPFieldInputState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.

Estende React.ComponentProps< typeof OTPFieldPrimitive.Input >. Aceita também os atributos padrão de um elemento React (305 não listados).

OTPFieldSeparator

Props de OTPFieldSeparator
PropTypeDefaultDescription
decorativebooleansem valor padrão
classNamestring | ((state: SeparatorState) => string | undefined)sem valor padrãoCSS class applied to the element, or a function that returns a class based on the component's state.
orientationOrientation'horizontal'The orientation of the separator.
renderReact.ReactElement<unknown, string | React.JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, SeparatorState>sem valor padrãoAllows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.
styleReact.CSSProperties | ((state: SeparatorState) => React.CSSProperties | undefined)sem valor padrãoStyle applied to the element, or a function that returns a style object based on the component's state.

Estende React.ComponentProps<typeof Separator>. Aceita também os atributos padrão de um elemento React (275 não listados).

prop obrigatória.

Composition

Uma OTPFieldInput por casa, na ordem do código; o separador fica entre elas, como irmão, e não conta como casa.

Composição de OTPField

OTPField

  • OTPFieldInput
  • OTPFieldSeparator

Metadata

Notas de acessibilidade

Teclado verificado por teste e em navegador: o campo inteiro custa um único Tab stop (foco roving), digitar avança para a próxima casa, Backspace apaga e volta, as setas andam entre casas, e colar um código preenche todas de uma vez e dispara onValueComplete. Leitor de tela verificado por teste: o campo é um group nomeado pelo label associado por htmlFor ao id, que o Base UI entrega à primeira casa; as demais casas recebem aria-label com a posição (Dígito 3 de 6), a descrição do grupo por aria-describedby diz para onde o código foi, e aria-invalid em cada casa carrega o estado de erro que o texto abaixo explica. Um campo desabilitado recusa entrada e sai da sequência de tabulação. Touch verificado em navegador com emulação de toque em viewport de 375px: cada casa mede 36x36 (40x40 no tamanho lg), seis casas cabem sem rolagem, e o toque numa casa a foca. Reduced motion verificado com prefers-reduced-motion: reduce — a transição de cor e de anel do foco não é movimento e permanece; não existe deslocamento para desligar. Varredura axe WCAG 2.2 AA limpa em light e dark.

Classificação

Layer
Primitive
Domínio
Domain-free (compartilhado)
Categoria
input
Status
Stable

Origem e distribuição

Fonte
coss registry / otp-field
Licença
MIT
Distribuição
Interna

Acessibilidade

  • Teclado: revisado
  • Leitor de tela: revisado
  • Touch: revisado
  • Reduced motion: revisado

Dependências

Pacotes
@base-ui/react
Ícones
Nenhum
Construído sobre
Separator
Usado por
Nenhum ainda