# OTP Field

> Collect a one-time code with one slot per character, paste support, and autofill.

Source: https://www.honestui.com/docs/components/otp-field

```tsx
"use client"

import {
  Field,
  FieldDescription,
  FieldLabel,
} from "@/components/honest-ui/ui/field"
import { OTPField } from "@/components/honest-ui/ui/otp-field"

export function OTPFieldDemo() {
  return (
    <Field name="verificationCode" className="w-fit">
      <FieldLabel>Verification code</FieldLabel>
      <OTPField length={6} />
      <FieldDescription>
        Enter the 6-digit code we sent to your phone ending in 0142.
      </FieldDescription>
    </Field>
  )
}

```

## Overview [#overview]

Use OTP Field to collect a short code that someone copies from somewhere else: a sign-in code sent by text message, an authenticator app code, a recovery code, an invite code. Each character gets its own slot, so people can check the code against the source one digit at a time and spot a missing or doubled character.

The field behaves like one input. Typing moves to the next slot, <kbd>Backspace</kbd> moves back, the arrow keys move between slots, and pasting a whole code fills every slot at once. The first slot sets `autocomplete="one-time-code"`, so iOS and Android can offer a code from an incoming message in one tap. The value is submitted under one `name` through a hidden input.

Use OTP Field only for short codes of fixed length. For passwords, use [Input](/docs/components/input) with `type="password"`. For numbers that people adjust, use [Number Field](/docs/components/number-field).

## Anatomy [#anatomy]

An OTP field has a root that owns the value and length, and one input per character. `OTPFieldGroup` joins neighbouring slots into one segmented control, and `OTPFieldSeparator` draws a dash between groups, so a code reads as `123-456`. With no children, `OTPField` renders `length` slots for you.

Every slot uses the [Input](/docs/components/input) styles: the same hairline edge, field fill, accent focus ring, danger edge when invalid, and muted fill when disabled. The slots are square and match the control height, so an OTP field lines up with buttons and inputs in the same row. Use `size="sm"` or `size="lg"` to match smaller or larger controls.

## Accessibility [#accessibility]

Label the field with `FieldLabel` inside a [Field](/docs/components/field), or with a native `label` whose `htmlFor` matches the root `id`. The label belongs to the first slot. Give every other slot an `aria-label` such as "Character 2 of 6", so screen readers say which slot has focus. The automatic slots follow this pattern already.

Put the length and format of the code in a `FieldDescription`, such as "Enter the 6-digit code we sent to your phone", and say where the code was sent. Report a wrong code with `FieldError` in words. A red edge on the slots is not enough on its own.

The slots set `inputMode` from `validationType`, so numeric codes open the number keypad on phones. Characters the validation rejects are never entered. Don't auto-advance past a wrong code or clear the slots when verification fails: people need to see what they typed to find the mistake.

## Installation [#installation]


  

  
    <CliBlock commands="[&#x22;otp-field&#x22;]" />
  

  
    
      
        Install the following dependencies:
      

      ```bash
      npm install @base-ui/react
      ```

      
        Copy and paste the following code into your project.
      

      ### components/ui/otp-field.tsx

```tsx
"use client"

import * as React from "react"
import { OTPField as OTPFieldPrimitive } from "@base-ui/react/otp-field"

import { cn } from "@/lib/utils"

type OTPFieldSize = "sm" | "default" | "lg"

const OTPFieldSizeContext = React.createContext<OTPFieldSize>("default")

function OTPField({
  className,
  children,
  length,
  size = "default",
  ...props
}: OTPFieldPrimitive.Root.Props & {
  size?: OTPFieldSize
}) {
  return (
    <OTPFieldSizeContext.Provider value={size}>
      <OTPFieldPrimitive.Root
        data-slot="otp-field"
        data-size={size}
        length={length}
        className={cn(
          "flex w-fit items-center gap-[var(--hui-space-2)] data-disabled:cursor-not-allowed",
          className
        )}
        {...props}
      >
        {/* With no children, render one slot per character. The first slot
            takes the field label; the rest name their position. */}
        {children ??
          Array.from({ length }, (_, index) => (
            <OTPFieldInput
              key={index}
              aria-label={
                index === 0 ? undefined : `Character ${index + 1} of ${length}`
              }
            />
          ))}
      </OTPFieldPrimitive.Root>
    </OTPFieldSizeContext.Provider>
  )
}

function OTPFieldInput({ className, ...props }: OTPFieldPrimitive.Input.Props) {
  const size = React.useContext(OTPFieldSizeContext)

  return (
    <OTPFieldPrimitive.Input
      data-hui=""
      data-slot="otp-field-input"
      className={cn(
        // Each slot is a square Input: same edge, fill, focus ring, and
        // invalid and disabled states, sized by the control height so it
        // lines up with buttons and inputs in the same row.
        "relative m-0 box-border",
        // Base UI selects a slot's character on focus so typing replaces it.
        // The selection stays, but it is painted transparent: the focus ring
        // already marks the active slot, and a highlight block reads as noise.
        // !important beats an app's unlayered ::selection color rule.
        "selection:bg-transparent! selection:text-[var(--hui-color-foreground-base-primary)]!",
        "aspect-square size-[var(--hui-density-control-height,36px)] min-w-0 rounded-[var(--hui-radius-2)] border-[0.5px] border-[var(--hui-color-border-field,var(--hui-color-border-base-tertiary))] bg-[var(--hui-color-background-field,var(--hui-color-background-base-primary))] p-0 text-center text-[var(--hui-color-foreground-base-primary)] tabular-nums caret-[var(--hui-color-border-accent-emphasis)] outline-none [font-size:var(--hui-font-size-regular)] [font-weight:var(--hui-font-weight-medium)] [line-height:var(--hui-line-height-regular)] motion-safe:[transition:var(--hui-transition-interactive)]",
        "placeholder:text-[var(--hui-color-foreground-base-tertiary)]",
        "not-focus:not-data-disabled:not-data-invalid:not-aria-invalid:not-read-only:hover:border-[var(--hui-color-border-field-hover,var(--hui-color-border-field,var(--hui-color-border-base-tertiary)))]",
        "focus:z-1 focus:border-[var(--hui-color-border-accent-emphasis)] focus:outline-2 focus:outline-solid focus:outline-transparent focus:shadow-[var(--hui-focus-ring-field)] focus:outline-offset-[var(--hui-focus-ring-offset-inset-border)]",
        "data-invalid:border-[var(--hui-color-border-danger-emphasis)] data-invalid:focus:border-[var(--hui-color-border-danger-emphasis-hover)] data-invalid:focus:shadow-[var(--hui-focus-ring-field-danger)] aria-invalid:border-[var(--hui-color-border-danger-emphasis)] aria-invalid:focus:border-[var(--hui-color-border-danger-emphasis-hover)] aria-invalid:focus:shadow-[var(--hui-focus-ring-field-danger)]",
        "read-only:bg-[var(--hui-color-background-base-secondary)] data-disabled:cursor-not-allowed data-disabled:border-[var(--hui-color-border-base-primary)] data-disabled:bg-[var(--hui-color-background-base-secondary)] data-disabled:text-[var(--hui-color-foreground-base-tertiary)]",
        "forced-colors:border-[CanvasText] forced-colors:focus:outline-[Highlight]",
        size === "sm" &&
          "size-[var(--hui-control-height-sm,var(--hui-space-8))] [font-size:var(--hui-font-size-control,13px)] [line-height:var(--hui-line-height-control,16px)]",
        size === "lg" &&
          "size-[var(--hui-control-height-lg,44px)] rounded-[var(--hui-radius-3)] [font-size:var(--hui-font-size-large)] [line-height:var(--hui-line-height-large)]",
        className
      )}
      {...props}
    />
  )
}

function OTPFieldGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="otp-field-group"
      className={cn(
        // Joined slots share one hairline edge: inner corners square off and
        // each slot overlaps its neighbour's border. The focused slot rises
        // above its neighbours so its ring is never clipped.
        "flex items-center *:data-[slot=otp-field-input]:rounded-none *:data-[slot=otp-field-input]:not-first:-ms-[0.5px] *:data-[slot=otp-field-input]:first:rounded-s-[var(--hui-radius-2)] *:data-[slot=otp-field-input]:last:rounded-e-[var(--hui-radius-2)] in-data-[size=lg]:*:data-[slot=otp-field-input]:first:rounded-s-[var(--hui-radius-3)] in-data-[size=lg]:*:data-[slot=otp-field-input]:last:rounded-e-[var(--hui-radius-3)]",
        className
      )}
      {...props}
    />
  )
}

function OTPFieldSeparator({
  className,
  children,
  ...props
}: React.ComponentProps<typeof OTPFieldPrimitive.Separator>) {
  return (
    <OTPFieldPrimitive.Separator
      data-slot="otp-field-separator"
      orientation="vertical"
      className={cn(
        "flex shrink-0 items-center justify-center text-[var(--hui-color-foreground-base-tertiary)]",
        className
      )}
      {...props}
    >
      {children ?? (
        <span
          aria-hidden="true"
          className="block h-[1.5px] w-[var(--hui-space-3)] rounded-[var(--hui-radius-full)] bg-current forced-colors:bg-[CanvasText]"
        />
      )}
    </OTPFieldPrimitive.Separator>
  )
}

export {
  OTPField,
  OTPField as InputOTP,
  OTPFieldInput,
  OTPFieldInput as InputOTPSlot,
  OTPFieldGroup,
  OTPFieldGroup as InputOTPGroup,
  OTPFieldSeparator,
  OTPFieldSeparator as InputOTPSeparator,
}

```

      
        Update the import paths to match your project setup.
      
    
  


## Usage [#usage]

```tsx
import {
  OTPField,
  OTPFieldGroup,
  OTPFieldInput,
  OTPFieldSeparator,
} from "@/components/ui/otp-field"
```

```tsx
<Field name="code">
  <FieldLabel>Verification code</FieldLabel>
  <OTPField length={6} />
</Field>
```

```tsx
<OTPField length={6}>
  <OTPFieldGroup>
    <OTPFieldInput />
    <OTPFieldInput aria-label="Character 2 of 6" />
    <OTPFieldInput aria-label="Character 3 of 6" />
  </OTPFieldGroup>
  <OTPFieldSeparator />
  <OTPFieldGroup>
    <OTPFieldInput aria-label="Character 4 of 6" />
    <OTPFieldInput aria-label="Character 5 of 6" />
    <OTPFieldInput aria-label="Character 6 of 6" />
  </OTPFieldGroup>
</OTPField>
```

Use `onValueComplete` to verify as soon as the last slot is filled, or `autoSubmit` to submit the surrounding form.

## Don't do this [#dont-do-this]

### Unnamed slots [#unnamed-slots]

```tsx
// Bad
<OTPField length={6}>
  {Array.from({ length: 6 }, (_, index) => <OTPFieldInput key={index} />)}
</OTPField>
```

```tsx
// Good
<OTPField length={6} />
```

Six unnamed inputs are announced as six identical "edit text" fields. Either let the root render its slots, or give every slot after the first an `aria-label` that states its position.

### Using slots for a password [#using-slots-for-a-password]

```tsx
// Bad
<OTPField length={12} validationType="none" mask />
```

```tsx
// Good
<Input type="password" autoComplete="current-password" />
```

Passwords vary in length and are saved by password managers. A fixed row of slots breaks both. OTP Field is for codes that someone reads from another place and types once.

## Examples [#examples]

### Grouped [#grouped]

Two groups of three slots, split by a separator.

```tsx
"use client"

import { Field, FieldLabel } from "@/components/honest-ui/ui/field"
import {
  OTPField,
  OTPFieldGroup,
  OTPFieldInput,
  OTPFieldSeparator,
} from "@/components/honest-ui/ui/otp-field"

export function OTPFieldGrouped() {
  return (
    <Field name="authenticatorCode" className="w-fit">
      <FieldLabel>Authenticator code</FieldLabel>
      <OTPField length={6}>
        <OTPFieldGroup>
          <OTPFieldInput />
          <OTPFieldInput aria-label="Character 2 of 6" />
          <OTPFieldInput aria-label="Character 3 of 6" />
        </OTPFieldGroup>
        <OTPFieldSeparator />
        <OTPFieldGroup>
          <OTPFieldInput aria-label="Character 4 of 6" />
          <OTPFieldInput aria-label="Character 5 of 6" />
          <OTPFieldInput aria-label="Character 6 of 6" />
        </OTPFieldGroup>
      </OTPField>
    </Field>
  )
}

```

### Alphanumeric recovery code [#alphanumeric-recovery-code]

`validationType="alphanumeric"` accepts letters, and `normalizeValue` converts them to uppercase.

```tsx
"use client"

import * as React from "react"

import {
  Field,
  FieldDescription,
  FieldLabel,
} from "@/components/honest-ui/ui/field"
import {
  OTPField,
  OTPFieldGroup,
  OTPFieldInput,
  OTPFieldSeparator,
} from "@/components/honest-ui/ui/otp-field"

export function OTPFieldAlphanumeric() {
  const [value, setValue] = React.useState("")

  return (
    <Field name="recoveryCode" className="w-fit">
      <FieldLabel>Recovery code</FieldLabel>
      <OTPField
        length={8}
        size="sm"
        validationType="alphanumeric"
        normalizeValue={(next) => next.toUpperCase()}
        value={value}
        onValueChange={setValue}
      >
        <OTPFieldGroup>
          <OTPFieldInput />
          <OTPFieldInput aria-label="Character 2 of 8" />
          <OTPFieldInput aria-label="Character 3 of 8" />
          <OTPFieldInput aria-label="Character 4 of 8" />
        </OTPFieldGroup>
        <OTPFieldSeparator />
        <OTPFieldGroup>
          <OTPFieldInput aria-label="Character 5 of 8" />
          <OTPFieldInput aria-label="Character 6 of 8" />
          <OTPFieldInput aria-label="Character 7 of 8" />
          <OTPFieldInput aria-label="Character 8 of 8" />
        </OTPFieldGroup>
      </OTPField>
      <FieldDescription>
        {value.length === 8
          ? `Ready to verify ${value.slice(0, 4)}-${value.slice(4)}.`
          : "Letters and numbers from one of your saved backup codes."}
      </FieldDescription>
    </Field>
  )
}

```

### Invalid code [#invalid-code]

A rejected code keeps its characters visible and states the error in words. The slots are masked with `mask`.

```tsx
"use client"

import * as React from "react"

import { Button } from "@/components/honest-ui/ui/button"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@/components/honest-ui/ui/field"
import { Form } from "@/components/honest-ui/ui/form"
import { OTPField } from "@/components/honest-ui/ui/otp-field"

// The only code this example accepts.
const EXPECTED_CODE = "246810"

export function OTPFieldInvalid() {
  const [error, setError] = React.useState(
    "That code didn’t match. Check the latest email and try again."
  )
  const [verified, setVerified] = React.useState(false)

  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    const code = String(new FormData(event.currentTarget).get("loginCode") ?? "")
    const matches = code === EXPECTED_CODE
    setVerified(matches)
    setError(
      matches
        ? ""
        : "That code didn’t match. Check the latest email and try again."
    )
  }

  return (
    <Form onSubmit={onSubmit} className="grid w-fit gap-[var(--hui-space-4)]">
      <Field name="loginCode" invalid={Boolean(error)}>
        <FieldLabel>Sign-in code</FieldLabel>
        <OTPField
          length={6}
          mask
          defaultValue="135790"
          onValueChange={() => setError("")}
        />
        <FieldError>{error}</FieldError>
        <FieldDescription aria-live="polite">
          {verified
            ? "Code verified. You’re signed in."
            : `Enter ${EXPECTED_CODE} to see the verified state.`}
        </FieldDescription>
      </Field>
      <Button type="submit" className="w-full">
        Verify
      </Button>
    </Form>
  )
}

```

## API reference [#api-reference]

`OTPField` accepts all Base UI OTP Field root props plus Honest UI's `size`:

| Prop                                       | Values                                     | Default         |
| ------------------------------------------ | ------------------------------------------ | --------------- |
| `length`                                   | number (required)                          | —               |
| `size`                                     | `sm`, `default`, `lg`                      | `default`       |
| `validationType`                           | `numeric`, `alpha`, `alphanumeric`, `none` | `numeric`       |
| `mask`                                     | boolean                                    | `false`         |
| `autoComplete`                             | string                                     | `one-time-code` |
| `autoSubmit`                               | boolean                                    | `false`         |
| `value` / `defaultValue` / `onValueChange` | string                                     | —               |
| `onValueComplete`                          | `(value) => void`                          | —               |
| `normalizeValue`                           | `(value) => string`                        | —               |

| Part                | Renders | Notes                                                          |
| ------------------- | ------- | -------------------------------------------------------------- |
| `OTPField`          | Div     | Owns the value; renders `length` slots when it has no children |
| `OTPFieldInput`     | Input   | One character slot                                             |
| `OTPFieldGroup`     | Div     | Joins its slots into one segmented control                     |
| `OTPFieldSeparator` | Div     | Separator between groups, drawn as a dash                      |

`InputOTP`, `InputOTPSlot`, `InputOTPGroup`, and `InputOTPSeparator` are exported as aliases for teams migrating from other libraries. The root carries `data-complete`, `data-filled`, and `data-focused`, and each slot carries `data-filled` and `data-invalid`. See the [Base UI OTP Field API](https://base-ui.com/react/components/otp-field#api-reference).
