# OTP Field

A segmented input for one-time passwords and verification codes.

- Category: Forms
- Page: https://wunderui.com/components/otp-field
- Tier: Free

## Install

```bash
npx wunderui-cli add otp-field
```

## Import

```tsx
import { OtpField, OtpCodeInput, OtpFieldCode, OtpFieldCodeProps, OtpFieldInput } from "@/components/ui/otp-field"
```

## Minimal usage

Then use it:

```tsx
import { Field, FieldDescription } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { OtpField, OtpFieldInput } from "@/components/ui/otp-field"

export function VerifyEmail() {
  return (
    <Field>
      <Label htmlFor="code" className="mb-1">
        Verification code
      </Label>
      <OtpField id="code" length={6} onValueComplete={(code) => console.log(code)}>
        {Array.from({ length: 6 }, (_, index) => (
          <OtpFieldInput key={index} aria-label={`Digit ${index + 1} of 6`} />
        ))}
      </OtpField>
      <FieldDescription>Enter the 6-digit code we sent to your email.</FieldDescription>
    </Field>
  )
}
```

Expected result: You see the label Verification code above six empty boxes. Typing 470921 moves focus from box to box and logs the code, and pasting six digits into the first box fills all six.

## Usage

```tsx
import { Field, FieldDescription } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { OtpField, OtpFieldInput } from "@/components/ui/otp-field"

export function Example() {
  return (
    <Field>
      <Label htmlFor="code" className="mb-1">
        Verification code
      </Label>
      <OtpField id="code" length={6}>
        {Array.from({ length: 6 }, (_, index) => (
          <OtpFieldInput key={index} aria-label={`Digit ${index + 1} of 6`} />
        ))}
      </OtpField>
      <FieldDescription>Enter the 6-digit code we sent to your email.</FieldDescription>
    </Field>
  )
}
```

## When to use

### Use OTP Field for

- A one-time code sent by email or SMS, typed once to confirm an address or a phone
- A code from an authenticator app when someone signs in with two steps
- A short PIN of 4 to 8 digits, masked or visible

### Use something else

- [Input](https://wunderui.com/components/input) for a code with dashes, a license key or any value longer than a few characters
- [Number Field](https://wunderui.com/components/number-field) for a quantity that people step up and down
- [Field](https://wunderui.com/components/field) for the label, message and validation around any control, including this one

## Keyboard

The group is one tab stop, with focus on the next empty slot or on the last one when the code is complete. Inside it the keys move between slots.

| Key | Action |
|---|---|
| `Tab` or `Shift+Tab` | Moves focus into and out of the group. The slots are not separate tab stops, so one Tab passes the whole code. A disabled field is skipped; a read-only one keeps its place. |
| `0-9` | Types a character into the focused slot and moves to the next. A character that the `validationType` rejects is ignored and reported in `onValueInvalid`. |
| `Backspace` | Clears the focused slot and moves to the previous one. In an empty slot it clears the previous slot first. |
| `Delete` | Removes the character of the focused slot. The characters after it move one slot forward. |
| `Ctrl+Backspace` or `Cmd+Backspace` | Clears the whole code and puts focus on the first slot. |
| `ArrowLeft` or `ArrowRight` | Moves focus to the previous or next slot. With Ctrl or Cmd it jumps to the first slot, or to the next empty one. |
| `Home` or `ArrowUp` | Moves focus to the first slot. |
| `End` or `ArrowDown` | Moves focus to the next empty slot, or to the last slot when the code is complete. |
| `Ctrl+V` or `Cmd+V` | Pastes into the focused slot and the ones after it. Characters the `validationType` rejects, and spaces, are dropped; a code that is too long is cut at `length`. |
| `Enter` | Sends the form that holds the field, like any native input. With `autoSubmit` the form is sent by itself when the last slot is filled. |

## Behavior

What the field does with the value, the focus and the label, and what it leaves to the page.

- **One value:** The field holds the code as one string, not one value per slot. Control it with a value and change handler, or let a default value keep it.
- **Auto-advance:** Typing moves focus to the next slot, Backspace moves it back, and arrow keys, Home and End move it freely. Clicking focuses a slot, and only the active slot is in the tab order.
- **Paste and autofill:** A paste spreads over the slots from the focused one, after rejected characters are removed. The first slot offers one-time-code autofill, so a phone can fill the whole code in one step.
- **Characters:** The validation type is numeric by default, or alpha, alphanumeric or none, and it sets the phone keyboard and filters typing and pasting. Mask turns the slots into password inputs for a PIN.
- **Completion:** The complete handler fires with the code when the last slot is filled, and again when a full code is pasted over a full one. Auto-submit sends the form at that moment.
- **Labelling:** The Label names the group and the first slot; slots after the first need your aria-label, or a screen reader calls them unnamed. FieldDescription and FieldError describe the group.
- **Invalid:** Inside an invalid Field every slot gets a red border and focus ring, and the fill stays white. The message is yours: write it in a FieldError under the slots, which replaces the helper line.
- **Disabled and read-only:** Disabled dims the slots to 40%, takes them out of the tab order and leaves the code out of the form data. Read-only keeps them focusable, blocks typing and paste, and uses the subtle tone.
- **Expired, verifying and verified:** No prop covers these states: expired is a read-only field with a warning and a Resend action, pending sets aria-busy with a spinner message, and verified is read-only with a check message.
- **Form data:** OtpField renders a hidden input that carries the whole code under the name, with required and form applied to it. The slots have no name, so the code is submitted once.
- **Motion:** The border colour of a slot changes quickly on hover and focus. Nothing moves or scales, and typing never animates.
- **Reduced motion:** With reduced motion the colour change stays, since it is a short fade and not movement. The spinner in a verifying message stops turning.

## Anatomy

- `Label`: The visible name of the code: a Label whose htmlFor matches the OtpField id. It names the group and the first slot, and a click on it focuses the field.
- `OtpField`: The group of slots: it holds the code as one string, moves focus and reports when the last slot is filled. A hidden input submits the code with the form.
- `OtpFieldInput`: One slot per character: a native input, 40 px square with an 8 px corner. Only one slot is in the tab order, so give every slot after the first an aria-label such as Digit 2 of 6.
- `Message`: The 12 px line under the slots: a FieldDescription with the rule, a FieldError with what to do, or a status for an expired, pending or verified code. An error replaces the helper.
- `OtpFieldCode`: The ready-made code field: 4 or 6 boxes of 56 by 64 px with an 8 px gap in a named group, every digit announced as Digit n of N. Use it instead of assembling OtpField and OtpFieldInput yourself; it replaces OtpCodeInput.
- `OtpCodeInput`

## Best practices

### When to use

- Use an OTP Field for a short code typed once: an email or SMS code, an authenticator code, a PIN. For dashed codes, long letter codes or a recovery key, use an Input.

### Do

- Render one OtpFieldInput per character and set the same number as the length. A six-digit code needs six slots.
- Give the field a visible Label whose htmlFor matches the id, and name every slot after the first with an aria-label such as Digit 2 of 6, so a screen reader announces the position.
- Leave autoComplete at its one-time-code default, so a phone offers the code from the message. The first slot takes the paste and spreads it across the slots.
- Check the code in the complete handler, or turn on auto-submit inside a form. The person should not have to find a button after the last digit.
- Say what to do when a code fails, with a message like That code is not correct, or one for an expired code with a Resend action. Keep what was typed so one digit can be fixed.

### Don't

- Don't change the length while the person is typing, and don't mix code lengths in one field. Render another field instead.
- Don't use an OTP Field for a long or free-form value. A long code is hard to check by eye in slots; use an Input.
- Don't use real or reused codes in examples, tests or screenshots. Use demo values such as 470921.

## API reference

### OtpField

| Prop | Type | Default | Description |
|---|---|---|---|
| length* | number |  | The number of slots, and so the length of the code. Required: the group uses it to cut a paste, detect completion and render the hidden input before the slots mount. Render the same number of `OtpFieldInput`. |
| autoComplete | string | 'one-time-code' | The `autocomplete` of the first slot and the hidden input. Defaults to `one-time-code`; the other slots are always `off`. |
| autoSubmit | boolean | false | Sends the form around the field when the code is complete, by calling `requestSubmit` on it. |
| className | string \| ((state: State) => string \| undefined) |  | CSS class applied to the element, or a function that returns a class based on the component's state. |
| defaultValue | string |  | The code the field starts with, for an uncontrolled field. |
| disabled | boolean | false | Dims the field to 40 %, removes it from the tab order and leaves the code out of the form data. |
| form | string |  | The `id` of a form elsewhere in the page that the hidden input belongs to, for a field that sits outside its form. |
| id | string |  | The `id` of the first slot; the others get `{id}-2`, `{id}-3` and so on. Use it as the `htmlFor` of the label. |
| inputMode | React.HTMLAttributes<HTMLInputElement>['inputMode'] |  | The virtual keyboard of the slots. The `validationType` sets a fitting one (`numeric` for digits, `text` for letters); set it only to override that. |
| mask | boolean | false | Shows the characters as dots by making the slots password inputs. Use it for a PIN. It does not change what the form submits. |
| name | string |  | The name under which the whole code is submitted with a form, through the hidden input. |
| normalizeValue | ((value: string) => string) |  | A function that changes the code after the filter, for example `(value) => value.toUpperCase()`. It runs on typed, pasted, controlled and default values. |
| onValueChange | ((value: string, eventDetails: OTPFieldRoot.ChangeEventDetails) => void) |  | Called with the new code and the reason (`input-change`, `input-clear`, `input-paste` or `keyboard`) whenever a character is typed, pasted or removed. |
| onValueComplete | ((value: string, eventDetails: OTPFieldRoot.CompleteEventDetails) => void) |  | Called with the code when the last slot is filled, or when a complete code is pasted over a complete one. It runs after `onValueChange`, so check the code here. |
| onValueInvalid | ((value: string, eventDetails: OTPFieldRoot.InvalidEventDetails) => void) |  | Called with the attempted text when typed or pasted characters are rejected by `validationType` or `normalizeValue`, before the value changes. Use it to show a hint such as `Digits only`. |
| readOnly | boolean | false | Keeps the field readable and focusable but blocks typing, paste and Backspace. It is submitted with the form. |
| render | React.ReactElement \| ComponentRenderFn<RenderFunctionProps, State> |  | Allows 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. |
| required | boolean | false | Marks the field as required. The form cannot be sent until every slot is filled. |
| style | React.CSSProperties \| ((state: State) => React.CSSProperties \| undefined) |  | Style applied to the element, or a function that returns a style object based on the component's state. |
| validationType | "none" \| "alpha" \| "numeric" \| "alphanumeric" | 'numeric' | Which characters the slots take: `numeric` (default), `alpha`, `alphanumeric` or `none`. It filters typing and paste and sets the keyboard on a phone. |
| value | string |  | The code, for a controlled field. A string with at most `length` characters; a shorter string leaves the last slots empty. |

Also accepts React.HTMLAttributes attributes.

### OtpCodeInput

| Prop | Type | Default | Description |
|---|---|---|---|
| aria-label | string |  | Names the group for screen readers; each digit is announced as "Digit n of N". |
| autoFocus | boolean |  |  |
| className | string |  |  |
| disabled | boolean |  |  |
| invalid | boolean |  |  |
| length | 4 \| 6 |  |  |
| onComplete | (value: string) => void |  |  |
| onValueChange | (value: string) => void |  |  |
| value | string |  |  |

### OtpFieldCode

| Prop | Type | Default | Description |
|---|---|---|---|
| aria-label | string |  | Names the group for a screen reader. Each box is announced as Digit n of N. "One-time code" by default. |
| autoFocus | boolean |  | Focuses the first box on mount. |
| className | string |  | Extra classes on the group, for example `justify-center` so the boxes centre in a narrow column. |
| disabled | boolean |  | Dims the boxes to 40 % and takes them out of the tab order. |
| invalid | boolean |  | Marks every box invalid: a red border and `aria-invalid`. The field shows no message, so write the text yourself. |
| length | 4 \| 6 | 6 | The number of boxes, 4 or 6. 6 by default. |
| onComplete | (value: string) => void |  | Called with the code once the last box is filled. Check the code here. |
| onValueChange | (value: string) => void |  | Called with the code whenever a digit is typed, pasted or removed. |
| value | string |  | The code, for a controlled field. A string of at most `length` digits. |

### OtpFieldInput

| Prop | Type | Default | Description |
|---|---|---|---|
| className | string \| ((state: State) => string \| undefined) |  | Extra classes on the slot, for example a different size. The default is 40 px square. |
| render | React.ReactElement \| ComponentRenderFn<RenderFunctionProps, State> |  | Allows 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. |
| style | React.CSSProperties \| ((state: State) => React.CSSProperties \| undefined) |  | Style applied to the element, or a function that returns a style object based on the component's state. |

Also accepts React.InputHTMLAttributes attributes.

## Examples

### Length: 4 digits, 6 digits, or 6 in two groups

```tsx
import { Field, FieldDescription } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { OtpField, OtpFieldInput } from "@/components/ui/otp-field"

export function Example() {
  return (
    <Field>
      <Label htmlFor="code" className="mb-1">
        Verification code
      </Label>
      <OtpField id="code" length={4}>
        {Array.from({ length: 4 }, (_, index) => (
          <OtpFieldInput key={index} aria-label={`Digit ${index + 1} of 4`} />
        ))}
      </OtpField>
      <FieldDescription>Enter the 4-digit code we sent to your email.</FieldDescription>
    </Field>
  )
}
```

### Characters: digits, letters and digits, or a masked PIN

```tsx
import { Field, FieldDescription } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { OtpField, OtpFieldInput } from "@/components/ui/otp-field"

export function Example() {
  return (
    <Field>
      <Label htmlFor="code" className="mb-1">
        Verification code
      </Label>
      <OtpField id="code" length={6}>
        {Array.from({ length: 6 }, (_, index) => (
          <OtpFieldInput key={index} aria-label={`Digit ${index + 1} of 6`} />
        ))}
      </OtpField>
      <FieldDescription>Enter the 6-digit code we sent to your email.</FieldDescription>
    </Field>
  )
}
```

### States: empty, partial, complete, invalid, expired, verifying, verified, disabled and read-only

```tsx
import { Field, FieldDescription } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { OtpField, OtpFieldInput } from "@/components/ui/otp-field"

export function Example() {
  return (
    <Field>
      <Label htmlFor="code" className="mb-1">
        Verification code
      </Label>
      <OtpField id="code" length={6}>
        {Array.from({ length: 6 }, (_, index) => (
          <OtpFieldInput key={index} aria-label={`Digit ${index + 1} of 6`} />
        ))}
      </OtpField>
      <FieldDescription>Enter the 6-digit code we sent to your email.</FieldDescription>
    </Field>
  )
}
```

### Code input: the ready-made field of 4 or 6 large boxes

```tsx
import { useState } from "react"
import { OtpFieldCode } from "@wunderui/react"

export function VerifyCode() {
  const [code, setCode] = useState("")

  return (
    <OtpFieldCode
      aria-label="Verification code"
      value={code}
      onValueChange={setCode}
      onComplete={(value) => console.log("Complete", value)}
      className="justify-center [&_[data-slot=otp-field-input]]:min-w-0"
    />
  )
}
```

## In context

### Email verification: the code is checked when the last digit is in

Type 482931 to see a verified code; any other code shows the error and keeps the digits. Paste works too, and Resend code clears the field.

```tsx
import { useState } from "react"
import { Check } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldError } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { OtpField, OtpFieldInput } from "@/components/ui/otp-field"
import { Spinner } from "@/components/ui/spinner"

export function Example() {
  const [value, setValue] = useState("")
  const [status, setStatus] = useState<"idle" | "verifying" | "verified" | "invalid">("idle")

  // Demo only: 482931 is the code. Check the code on your server.
  const verify = (code: string) => {
    setStatus("verifying")
    window.setTimeout(() => setStatus(code === "482931" ? "verified" : "invalid"), 800)
  }

  return (
    <Field invalid={status === "invalid"}>
      <Label htmlFor="email-code" className="mb-1">
        Verification code
      </Label>
      <OtpField
        id="email-code"
        length={6}
        value={value}
        readOnly={status === "verified"}
        aria-busy={status === "verifying"}
        onValueChange={(next) => {
          setValue(next)
          setStatus("idle")
        }}
        onValueComplete={verify}
      >
        {Array.from({ length: 6 }, (_, index) => (
          <OtpFieldInput key={index} aria-label={`Digit ${index + 1} of 6`} />
        ))}
      </OtpField>
      {status === "idle" && <FieldDescription>We sent a 6-digit code to info@wunderui.com.</FieldDescription>}
      {status === "invalid" && <FieldError match>That code is not correct. Check it and try again.</FieldError>}
      {status === "verifying" && (
        <p role="status" className="flex items-center gap-2 text-xs text-text-secondary">
          <Spinner aria-hidden className="size-3.5 motion-reduce:animate-none" /> Verifying...
        </p>
      )}
      {status === "verified" && (
        <p role="status" className="flex items-center gap-2 text-xs text-text-success">
          <Check className="size-3.5" aria-hidden /> Email verified.
        </p>
      )}
      <Button
        variant="link"
        size="sm"
        className="self-start"
        onClick={() => {
          setValue("")
          setStatus("idle")
        }}
      >
        Resend code
      </Button>
    </Field>
  )
}
```

### Two-factor sign-in: the form is sent by the last digit

Auto-submit sends the form as soon as the sixth digit is in, so there is nothing to find after typing. The button stays for anyone who prefers it.

```tsx
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { OtpField, OtpFieldInput } from "@/components/ui/otp-field"

export function Example() {
  const [signedIn, setSignedIn] = useState(false)

  return (
    <form
      className="flex flex-col gap-4"
      onSubmit={(event) => {
        event.preventDefault()
        setSignedIn(true)
      }}
    >
      <Field>
        <Label htmlFor="app-code" className="mb-1">
          Authentication code
        </Label>
        <OtpField id="app-code" name="code" length={6} autoSubmit required>
          {Array.from({ length: 6 }, (_, index) => (
            <OtpFieldInput key={index} aria-label={`Digit ${index + 1} of 6`} />
          ))}
        </OtpField>
        <FieldDescription>Open your authenticator app and enter the 6-digit code.</FieldDescription>
      </Field>
      <Button type="submit" variant="gradient">
        Sign in
      </Button>
      <p aria-live="polite" className="min-h-5 text-sm text-text-secondary">
        {signedIn ? "Signed in to the WunderUI workspace." : ""}
      </p>
    </form>
  )
}
```

### PIN approval: masked digits and an action that waits for the fourth one

The digits show as dots. The Approve button stays disabled until the PIN is complete, and the result is announced politely.

```tsx
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { OtpField, OtpFieldInput } from "@/components/ui/otp-field"

export function Example() {
  const [pin, setPin] = useState("")
  const [approved, setApproved] = useState(false)

  return (
    <div className="flex flex-col gap-4">
      <Field>
        <Label htmlFor="pin" className="mb-1">
          PIN
        </Label>
        <OtpField id="pin" length={4} mask value={pin} onValueChange={setPin}>
          {Array.from({ length: 4 }, (_, index) => (
            <OtpFieldInput key={index} aria-label={`PIN digit ${index + 1} of 4`} />
          ))}
        </OtpField>
        <FieldDescription>Approve the transfer of $1,250.00 to Daniel Okafor.</FieldDescription>
      </Field>
      <Button variant="gradient" disabled={pin.length < 4} onClick={() => setApproved(true)}>
        Approve transfer
      </Button>
      <p aria-live="polite" className="min-h-5 text-sm text-text-secondary">
        {approved ? "Transfer approved." : ""}
      </p>
    </div>
  )
}
```

## For AI agents

`get_component("otp-field")`

Hand your agent this page as Markdown or the WunderUI MCP server, not a screenshot.
