# OTP Input

A one-time code with a box for each character.

Source: [otp-input.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/otp-input.tsx)

```tsx
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { OTPInput } from "@/components/ui/otp-input";

export default function OTPInputBasic() {
  return (
    <Field className="w-fit">
      <FieldLabel>Verification code</FieldLabel>
      <OTPInput length={6} />
      <FieldDescription>Enter the 6-digit code we sent to tony@example.com.</FieldDescription>
    </Field>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/otp-input
```

## Usage

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import { OTPInput } from "@/components/ui/otp-input";

export function CodeField() {
  return (
    <Field>
      <FieldLabel>Code</FieldLabel>
      <OTPInput length={4} />
    </Field>
  );
}
```

`OTPInput` renders a box for each of its `length` characters. In a [Field](https://ui.jarv.is/components/field.md), the
`FieldLabel` labels the first box, and screen readers announce each of the others by its position,
such as "Character 2 of 4". To change that wording, lay out the boxes yourself and give each
`OTPInputSlot` an `aria-label`.

To lay out the boxes yourself, pass `OTPInput` the parts as children, as in
[Composing the boxes](#composing-the-boxes).

## Composition

- `OTPInput`
  - `OTPInputSlot`
  - `OTPInputGroup`
  - `OTPInputSeparator`

## Examples

### Checking the code

`onValueComplete` is called once every box is filled. When the code is wrong, set `invalid` on the
[`Field`](https://ui.jarv.is/components/field.md) to mark every box invalid, and show a `FieldError`.

```tsx
"use client";

import * as React from "react";

import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field";
import { OTPInput } from "@/components/ui/otp-input";
import { toast } from "@/components/ui/toast";

export default function OTPInputVerify() {
  const [code, setCode] = React.useState("");
  const [invalid, setInvalid] = React.useState(false);

  return (
    <Field invalid={invalid} className="w-fit">
      <FieldLabel>Sign-in code</FieldLabel>
      <OTPInput
        length={6}
        value={code}
        onValueChange={(value) => {
          setCode(value);
          setInvalid(false);
        }}
        onValueComplete={(value) => {
          if (value === "424242") {
            setCode("");
            toast.add({ title: "Code verified", type: "success" });
          } else {
            setInvalid(true);
          }
        }}
      />
      {invalid ? (
        <FieldError>That code didn&apos;t work. Check it and try again.</FieldError>
      ) : (
        <FieldDescription>Try 424242, or any other code to see an error.</FieldDescription>
      )}
    </Field>
  );
}
```

### Groups

`groupSize` splits a long code into groups of that many boxes, with a separator between them.

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import { OTPInput } from "@/components/ui/otp-input";

export default function OTPInputGrouped() {
  return (
    <Field className="w-fit">
      <FieldLabel>Authenticator code</FieldLabel>
      <OTPInput length={6} groupSize={3} />
    </Field>
  );
}
```

### Composing the boxes

For groups that `groupSize` can't make, give `OTPInput` an `OTPInputSlot` for each character,
arranged in `OTPInputGroup`s with an `OTPInputSeparator` between them. In this example, a TV's
pairing code is split into a group of three characters and a group of four.

```tsx
"use client";

import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import {
  OTPInput,
  OTPInputGroup,
  OTPInputSeparator,
  OTPInputSlot,
} from "@/components/ui/otp-input";

export default function OTPInputDeviceCode() {
  return (
    <Field className="w-fit">
      <FieldLabel>TV code</FieldLabel>
      <OTPInput
        length={7}
        validationType="alphanumeric"
        normalizeValue={(value) => value.toUpperCase()}
      >
        <OTPInputGroup>
          <OTPInputSlot />
          <OTPInputSlot />
          <OTPInputSlot />
        </OTPInputGroup>
        <OTPInputSeparator />
        <OTPInputGroup>
          <OTPInputSlot />
          <OTPInputSlot />
          <OTPInputSlot />
          <OTPInputSlot />
        </OTPInputGroup>
      </OTPInput>
      <FieldDescription>Enter the code shown on your TV, such as ABC-DEFG.</FieldDescription>
    </Field>
  );
}
```

### Large

Set `size="lg"` on `OTPInput` for larger boxes, or `size="sm"` for smaller ones.

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import { OTPInput } from "@/components/ui/otp-input";

export default function OTPInputLarge() {
  return (
    <Field className="w-fit">
      <FieldLabel>Device code</FieldLabel>
      <OTPInput length={6} size="lg" groupSize={3} />
    </Field>
  );
}
```

### Letters and numbers

`OTPInput` accepts only digits by default. Set `validationType="alphanumeric"` to allow letters, and
`normalizeValue` to transform what's typed, such as converting it to uppercase.

```tsx
"use client";

import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { OTPInput } from "@/components/ui/otp-input";

export default function OTPInputAlphanumeric() {
  return (
    <Field className="w-fit">
      <FieldLabel>Recovery code</FieldLabel>
      <OTPInput
        length={8}
        validationType="alphanumeric"
        normalizeValue={(value) => value.toUpperCase()}
        groupSize={4}
      />
      <FieldDescription>Letters are converted to uppercase.</FieldDescription>
    </Field>
  );
}
```

### Masked

`mask` hides the characters, like a password field.

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import { OTPInput } from "@/components/ui/otp-input";

export default function OTPInputMasked() {
  return (
    <Field className="w-fit">
      <FieldLabel>PIN</FieldLabel>
      <OTPInput length={4} mask />
    </Field>
  );
}
```

### Disabled

```tsx
import { Field, FieldLabel } from "@/components/ui/field";
import { OTPInput } from "@/components/ui/otp-input";

export default function OTPInputDisabled() {
  return (
    <Field disabled className="w-fit">
      <FieldLabel>Previous PIN</FieldLabel>
      <OTPInput length={4} defaultValue="4821" mask />
    </Field>
  );
}
```

## Props

| Part | Extends |
| --- | --- |
| `OTPInput` | [`OTPField.Root`](https://base-ui.com/react/components/otp-field#root) |
| `OTPInputGroup` | `<div>` |
| `OTPInputSlot` | [`OTPField.Input`](https://base-ui.com/react/components/otp-field#input) |
| `OTPInputSeparator` | [`OTPField.Separator`](https://base-ui.com/react/components/otp-field#separator) |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### OTPInput

| Prop               | Type                                                                                      | Default           | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------ | ----------------------------------------------------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id?`              | `string`                                                                                  | —                 | The id of the first input element. Subsequent inputs derive their ids from it (`{id}-2`, `{id}-3`, and so on).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `autoComplete?`    | `string`                                                                                  | `'one-time-code'` | The input autocomplete attribute. Applied to the first slot and hidden validation input.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `form?`            | `string`                                                                                  | —                 | A 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `length`           | `number`                                                                                  | —                 | The number of OTP input slots. Required so the root can clamp values, detect completion, and generate consistent validation markup before all slots hydrate.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `autoSubmit?`      | `boolean`                                                                                 | `false`           | Whether to submit the owning form when the OTP becomes complete.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `mask?`            | `boolean`                                                                                 | `false`           | Whether the slot inputs should mask entered characters. Pass `type` directly to individual `<OTPField.Input>` parts to use a custom input type.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `inputMode?`       | `"decimal" \| "email" \| "none" \| "numeric" \| "search" \| "tel" \| "text" \| "url"`     | —                 | The 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `validationType?`  | `"alpha" \| "alphanumeric" \| "none" \| "numeric"`                                        | `'numeric'`       | The type of input validation to apply to the OTP value.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `normalizeValue?`  | `((value: string) => string)`                                                             | —                 | Function 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`. |
| `required?`        | `boolean`                                                                                 | `false`           | Whether the user must enter a value before submitting a form.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `disabled?`        | `boolean`                                                                                 | `false`           | Whether the component should ignore user interaction.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `readOnly?`        | `boolean`                                                                                 | `false`           | Whether the user should be unable to change the field value.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `name?`            | `string`                                                                                  | —                 | Identifies the field when a form is submitted.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `value?`           | `string`                                                                                  | —                 | The OTP value.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `defaultValue?`    | `string`                                                                                  | —                 | The uncontrolled OTP value when the component is initially rendered.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `onValueChange?`   | `((value: string, eventDetails: OTPField.Root.ChangeEventDetails) => void)`               | —                 | Callback 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                                                                                                                                                                                                                                                                                                                                  |
| `onValueInvalid?`  | `((value: string, eventDetails: OTPField.Root.InvalidEventDetails) => void)`              | —                 | Callback 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.                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `onValueComplete?` | `((value: string, eventDetails: OTPField.Root.CompleteEventDetails) => void)`             | —                 | Callback 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.                                                                                                                                                                                                                             |
| `size?`            | `"default" \| "lg" \| "sm"`                                                               | `"default"`       | The size of each slot: `sm` 24px, `default` 28px, `lg` 32px square.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `groupSize?`       | `number`                                                                                  | —                 | Splits the boxes into groups of this many, with a separator between groups. Applies only when `OTPInput` renders the boxes itself, without children.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `className?`       | `string \| ((state: OTPFieldRootState) => string \| undefined)`                           | —                 | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `style?`           | `React.CSSProperties \| ((state: OTPFieldRootState) => React.CSSProperties \| undefined)` | —                 | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `render?`          | `ComponentRenderFn<HTMLProps, OTPFieldRootState> \| React.ReactElement`                   | —                 | 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                |

### OTPInputGroup

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | 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. |

### OTPInputSlot

| Prop         | Type                                                                                                                                                  | Default | Description                                                                                                                                                                               |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string \| ((state: OTPFieldInputState) => string \| undefined)`                                                                                      | —       | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`     | `React.CSSProperties \| ((state: OTPFieldInputState) => React.CSSProperties \| undefined)`                                                            | —       | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`    | `ComponentRenderFn<React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, OTPFieldInputState> \| React.ReactElement` | —       | 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. |

### OTPInputSeparator

| Prop           | Type                                                                                   | Default        | Description                                                                                                                                                                               |
| -------------- | -------------------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `orientation?` | `"horizontal" \| "vertical"`                                                           | `'horizontal'` | The orientation of the separator.                                                                                                                                                         |
| `className?`   | `string \| ((state: SeparatorState) => string \| undefined)`                           | —              | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`       | `React.CSSProperties \| ((state: SeparatorState) => React.CSSProperties \| undefined)` | —              | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`      | `ComponentRenderFn<HTMLProps, SeparatorState> \| React.ReactElement`                   | —              | 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. |
