# OtpField

Accepts a one-time passcode, one character per slot.

[View source and API](https://github.com/tempoxyz/ds/blob/main/src/web/components/OtpField.tsx)

Figma: [Inputs/Code Input](https://www.figma.com/design/yE96kcymnNR88PJp6G1sPs?node-id=5227-3204) (`OtpField.Root`)

## Overview

OtpField renders one slot per character of a one-time passcode. Label it with `Field.Label` or a `<label>`, which also names the first slot.

## Examples

### Basic

```tsx
import { OtpField, style } from '@tempoxyz/ds'
import { useState } from 'react'

const code = '123456'

const messages = {
  idle: `Enter ${code} to verify`,
  invalid: 'Wrong code. Delete a digit and try again.',
  success: 'Code accepted',
}

export function Demo() {
  const [value, setValue] = useState('')
  const status = (() => {
    if (value.length < code.length) return 'idle'
    if (value === code) return 'success'
    return 'invalid'
  })()

  return (
    <div {...styles.column()}>
      <OtpField.Root
        aria-label="Verification code"
        invalid={status === 'invalid'}
        length={6}
        onValueChange={setValue}
        success={status === 'success'}
        value={value}
      />
      <output>{messages[status]}</output>
    </div>
  )
}

namespace styles {
  export const column = style({
    alignItems: 'flex-start',
    display: 'flex',
    flexDirection: 'column',
    gap: '24',
  })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/OtpField/Basic.tsx)

### Invalid

Set `invalid` to fill the slots red and nudge them sideways.

```tsx
import { OtpField, style } from '@tempoxyz/ds'

export function Demo() {
  return (
    <div {...styles.column()}>
      <OtpField.Root aria-label="Invalid code" defaultValue="000000" invalid length={6} />
    </div>
  )
}

namespace styles {
  export const column = style({
    alignItems: 'flex-start',
    display: 'flex',
    flexDirection: 'column',
    gap: '24',
  })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/OtpField/Invalid.tsx)

### Success

Set `success` to fill the slots green.

```tsx
import { OtpField, style } from '@tempoxyz/ds'

export function Demo() {
  return (
    <div {...styles.column()}>
      <OtpField.Root aria-label="Verified code" defaultValue="123456" length={6} success />
    </div>
  )
}

namespace styles {
  export const column = style({
    alignItems: 'flex-start',
    display: 'flex',
    flexDirection: 'column',
    gap: '24',
  })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/OtpField/Success.tsx)

### Disabled

```tsx
import { OtpField, style } from '@tempoxyz/ds'

export function Demo() {
  return (
    <div {...styles.column()}>
      <OtpField.Root aria-label="Disabled code" defaultValue="123" disabled length={6} />
    </div>
  )
}

namespace styles {
  export const column = style({
    alignItems: 'flex-start',
    display: 'flex',
    flexDirection: 'column',
    gap: '24',
  })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/OtpField/Disabled.tsx)

## Anatomy

Import the component and assemble its parts.

```tsx
import { OtpField } from '@tempoxyz/ds'

<OtpField.Root>
  <OtpField.Input />
</OtpField.Root>
```

## Guidelines

### When to Use

* Verify an email address or phone number with a code sent to it.
* Confirm a sensitive action with an authenticator code, such as a new API key or withdrawal address.
* Enter a fixed-length backup code. If it mixes letters and digits, set `validationType="alphanumeric"`.

### When Not to Use

* Use [TextInput](/docs/components/text-input) for codes without a fixed length, such as invite or promo codes.
* Use [TextInput](/docs/components/text-input) with `type="password"` for passwords.
* Use [SecretValue](/docs/components/secret-value) to show a key or recovery phrase.

### Support Autofill and Paste

A paste drops spaces and rejected characters, so 482 913 and 482-913 both work. Some people can't type the code at all.

* Set `length` to the exact length of the code.
* End SMS messages with an origin-bound line, such as `@wallet.tempo.xyz #482913`. Supporting browsers then offer the code only on your domain.
* Use `onValueInvalid` to report characters dropped from pasted text.

**Do:** Use one OtpField, so autofill and paste fill every slot.

```tsx
/**
 * Do example for "Support Autofill and Paste" on the OtpField page.
 * Use one OtpField, so autofill and paste fill every slot.
 * @module
 */
import { Badge, Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <OtpField.Root defaultValue="482913" length={6} />
      <span {...styles.suggestion()}>
        <Badge size="small">From Messages: 482913</Badge>
      </span>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })

  export const suggestion = style({ display: 'flex' })
}
```

**Don't:** Split the code across separate inputs or intercept paste.

```tsx
/**
 * Don't example for "Support Autofill and Paste" on the OtpField page.
 * Don't split the code across separate inputs or intercept paste.
 * @module
 */
import { Field, style, TextInput } from '@tempoxyz/ds'

const digits = ['4', '8', '2', '9', '1', '3']

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <div {...styles.row()}>
        {digits.map((digit, index) => (
          <TextInput.Group key={index} {...styles.slot()}>
            <TextInput.Control
              aria-label={`Digit ${index + 1}`}
              defaultValue={digit}
              maxLength={1}
            />
          </TextInput.Group>
        ))}
      </div>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })

  export const row = style({ display: 'flex', gap: '8' })

  export const slot = style({ minWidth: '0 !custom', width: '2.5rem !custom' })
}
```

### Say Where the Code Went

Name the destination and the expiry in `Field.Description`.

**Do:** Say where you sent the code and when it expires.

```tsx
/**
 * Do example for "Say Where the Code Went" on the OtpField page.
 * Say where you sent the code and when it expires.
 * @module
 */
import { Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <OtpField.Root length={6} />
      <Field.Description>Sent to alice@example.com. It expires in 10 minutes.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })
}
```

**Don't:** Ask for a code without saying where to find it.

```tsx
/**
 * Don't example for "Say Where the Code Went" on the OtpField page.
 * Don't ask for a code without saying where to find it.
 * @module
 */
import { Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <OtpField.Root length={6} />
      <Field.Description>Enter the code.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })
}
```

### Verify When the Code Is Complete

Start verification in `onValueComplete` when the last slot fills, or set `autoSubmit` to submit the owning form. A separate confirm step adds a click.

**Do:** Verify the code as soon as the last slot fills, and show progress below it.

```tsx
/**
 * Do example for "Verify When the Code Is Complete" on the OtpField page.
 * Verify the code as soon as the last slot fills, and show progress below it.
 * @module
 */
import { Field, LoadingDots, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <OtpField.Root defaultValue="482913" length={6} readOnly />
      <Field.Description>
        Verifying <LoadingDots aria-label="Verifying code" />
      </Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })
}
```

**Don't:** Add a Verify button after a complete code.

```tsx
/**
 * Don't example for "Verify When the Code Is Complete" on the OtpField page.
 * Don't add a Verify button after a complete code.
 * @module
 */
import { Button, Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.column()}>
      <Field.Root>
        <Field.Label>Verification code</Field.Label>
        <OtpField.Root defaultValue="482913" length={6} />
      </Field.Root>
      <Button>Verify code</Button>
    </div>
  )
}

namespace styles {
  export const column = style({
    alignItems: 'flex-start',
    display: 'flex',
    flexDirection: 'column',
    gap: '16',
  })
}
```

Set `readOnly` while the request runs, with a [Spinner](/docs/components/spinner) or [LoadingDots](/docs/components/loading-dots) nearby. Then set `success` or `invalid`.

### Explain a Rejected Code in Text

`invalid` only colors and nudges the slots. Add a `Field.Error` with the next step, and keep the entered code so people can fix a typo.

**Do:** Pair `invalid` with a message that says what to do.

```tsx
/**
 * Do example for "Explain a Rejected Code in Text" on the OtpField page.
 * Pair `invalid` with a message that says what to do.
 * @module
 */
import { Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root invalid {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <OtpField.Root defaultValue="482913" invalid length={6} />
      <Field.Error match>That code didn't match. Check your latest email.</Field.Error>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })
}
```

**Don't:** Rely on the red slots alone.

```tsx
/**
 * Don't example for "Explain a Rejected Code in Text" on the OtpField page.
 * Don't rely on the red slots alone.
 * @module
 */
import { Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root invalid {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <OtpField.Root defaultValue="482913" invalid length={6} />
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })
}
```

### Offer a New Code

Place a `tertiary` [Button](/docs/components/button) such as Send a new code below the field. After a resend, disable it for a short cooldown and state when it returns.

**Do:** State when a disabled resend returns.

```tsx
/** Do example for "Offer a New Code" on the OtpField page: state when a disabled resend returns. @module */
import { Button, Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.stack()}>
      <Field.Root>
        <Field.Label>Verification code</Field.Label>
        <OtpField.Root length={6} />
        <Field.Description>Sent to alice@example.com.</Field.Description>
      </Field.Root>
      <span {...styles.action()}>
        <Button disabled size="small" variant="tertiary">
          Send a new code in 30s
        </Button>
      </span>
    </div>
  )
}

namespace styles {
  export const action = style({ display: 'flex' })

  export const stack = style({
    display: 'grid',
    gap: '8',
    maxWidth: '18rem !custom',
    width: '100% !custom',
  })
}
```

**Don't:** Disable the resend button without saying why.

```tsx
/**
 * Don't example for "Offer a New Code" on the OtpField page.
 * Don't disable the resend button without saying why.
 * @module
 */
import { Button, Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.stack()}>
      <Field.Root>
        <Field.Label>Verification code</Field.Label>
        <OtpField.Root length={6} />
        <Field.Description>Sent to alice@example.com.</Field.Description>
      </Field.Root>
      <span {...styles.action()}>
        <Button disabled size="small" variant="tertiary">
          Send a new code
        </Button>
      </span>
    </div>
  )
}

namespace styles {
  export const action = style({ display: 'flex' })

  export const stack = style({
    display: 'grid',
    gap: '8',
    maxWidth: '18rem !custom',
    width: '100% !custom',
  })
}
```

### Leave Codes Visible

Short-lived codes are safe to show. Set `mask` only for codes that stay valid, such as a PIN, or on shared screens.

**Do:** Show a short-lived code, so people can check it against the message.

```tsx
/**
 * Do example for "Leave Codes Visible" on the OtpField page.
 * Show a short-lived code, so people can check it against the message.
 * @module
 */
import { Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <OtpField.Root defaultValue="482913" length={6} />
      <Field.Description>It expires in 10 minutes.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })
}
```

**Don't:** Mask a code that expires in minutes.

```tsx
/**
 * Don't example for "Leave Codes Visible" on the OtpField page.
 * Don't mask a code that expires in minutes.
 * @module
 */
import { Field, OtpField, style } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.field()}>
      <Field.Label>Verification code</Field.Label>
      <OtpField.Root defaultValue="482913" length={6} mask />
      <Field.Description>It expires in 10 minutes.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const field = style({ maxWidth: '18rem !custom', width: '100% !custom' })
}
```

## Content

* **Label:** Verification code, or the source, such as Authenticator code.
* **Term:** Write code, not OTP or one-time password.

## Accessibility

OtpField renders a group of single-character text inputs.

### Semantics

* **OtpField.Root (group):** Groups the slots into one control. Its `aria-label` names the group.
* **Slots (inputmode=numeric):** Each slot is a native text input with a numeric keyboard by default.
* **Autofill (one-time-code):** Set on the first slot, so browsers can offer a code from SMS or email.
* **Invalid and Success (aria-invalid):** `invalid` marks every slot invalid. `success` sets no ARIA state, so announce the result in text.
* **Disabled (disabled):** Disables every slot, so none of the slots takes focus or accepts input.

### Keyboard

* **Enter the Field (Tab):** Moves focus to the active slot. Only one slot is in the tab order.
* **Type a Character:** Fills the slot and moves to the next one. Ignores characters that `validationType` rejects.
* **Delete Backward (Backspace):** Removes the previous character and moves back one slot.
* **Delete Forward (Delete):** Removes the character in the focused slot and shifts the rest left.
* **Move Between Slots (Left or Right Arrow):** Moves focus one slot at a time between filled slots and the first empty one.
* **Go to the First Slot (Home):** Moves focus to the first slot, whether or not the slots are filled.
* **Go to the End (End):** Moves to the first empty slot, or to the last slot when every slot is filled.
* **Paste a Code (Paste):** Fills the slots from the focused one and drops spaces and rejected characters.

### Size and Motion

* **Slot Size (56px):** Slots are 56px tall and fill the field. The focused slot is 3px wider than the others, and a message in `Field.Root` sits 8px below them. Slots shrink to fit narrow screens instead of wrapping.
* **Reduced Motion (reduce):** If the reader prefers reduced motion, the nudge stops.

### Your Responsibilities

* **Label the Slots (Field.Label):** Use a field label, which names the first slot. A root `aria-label` names only the group.
* **Announce the Result (output):** State the result in text beside the field, such as "Code accepted" or "Wrong code".

## Related

[TextInput](/docs/components/text-input)

Use for variable-length codes.

[Field](/docs/components/field)

Use for labels, descriptions, and errors.

[SecretValue](/docs/components/secret-value)

Use for showing keys and secrets.

[Errors and Validation](/docs/patterns/errors-and-validation)

Covers explaining rejected values.
