---
title: PinInput
description: Enter pins and verification codes with automatic focus advance and
  clipboard support.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# PinInput

> Enter pins and verification codes with automatic focus advance and clipboard support.

## Anatomy

```text
PinInput [component; slot=root]
├── input [slot]
└── separator [slot]
```

## Usage

Use `PinInput` for verification codes, OTPs, or numeric PINs. It renders one single-character input
per slot.

```tsx
import { PinInput } from 'moraine'

export function Example() {
  return <PinInput length={6} onComplete={(code) => console.log(code)} />
}
```

### Values and completion

`length` sets the number of slots (default `5`). `value` and `defaultValue` accept a joined string
(`'123456'`) or an array with one character per slot, and are filtered by `validationType` and
truncated to `length`. `onValueChange` always receives an array of `length` entries with `''` for
empty slots; use `.join('')` for the string. `onComplete` receives the joined string once every slot
is filled. Set `name` to submit the joined value through a hidden input, and `form` to associate
the control with a `<form>` outside its ancestors. A native form reset restores `defaultValue`.

```tsx
<PinInput length={4} value={code()} onValueChange={(chars) => setCode(chars.join(''))} />
```

### Validation type and mask

`validationType` controls which characters a slot accepts: `'number'` (digits), `'alpha'` (letters),
`'alphanumeric'`, or `'text'` (any non-whitespace character, the default). It also picks the default
`inputMode`; set `inputMode` to override it. Use `mask` to render the slots as password inputs and
conceal the entered characters.

```tsx
<PinInput validationType="number" mask length={4} />
```

### OTP autofill

Use `otp` to set `autocomplete="one-time-code"`, so mobile devices can fill codes from SMS messages.

```tsx
<PinInput otp length={6} />
```

The hidden input, rendered when `name` is set, also accepts pasted or autofilled full codes and
distributes them across the slots.

### Normalization and invalid input

Use `normalizeValue` to transform proposed values after `validationType` filtering, and
`onValueInvalid` to observe refused characters, with a `reason` of
`'patternMismatch'` or `'tooLong'`. `normalizeValue` runs on string
`value` and `defaultValue` and on typed, pasted, or autofilled text; it must be idempotent.

```tsx
<PinInput
  length={6}
  validationType="alphanumeric"
  normalizeValue={(value) => value.toUpperCase()}
  onValueInvalid={({ value, reason }) => console.warn(reason, value)}
/>
```

### Auto-submit

Use `autoSubmit` to call `requestSubmit()` on the owning form right after `onComplete`, which runs
native validation and fires a `submit` event. The form comes from `form`, the inputs, or the closest
ancestor `<form>`; nothing happens without one.

```tsx
<form>
  <PinInput name="code" length={6} autoSubmit />
</form>
```

### Placeholder

Use `placeholder` to show a character hint in empty slots that are not focused:

```tsx
<PinInput length={6} placeholder="○" />
```

### Separators

Use `groupSize` to insert separators between groups of slots. Pass `true` to split the slots in
half, a number for fixed-size groups, or an array of consecutive group sizes. Use `separatorRender`
to replace the default `•` separator.

```tsx
<PinInput length={6} groupSize />
<PinInput length={6} groupSize={3} />
<PinInput length={7} groupSize={[3, 1, 3]} />
```

### Keyboard interaction

| Key                                        | Description                                                                     |
| ------------------------------------------ | ------------------------------------------------------------------------------- |
| <kbd>ArrowLeft</kbd>                       | Moves focus to the previous input (in RTL, the next).                           |
| <kbd>ArrowRight</kbd>                      | Moves focus to the next input (in RTL, the previous).                           |
| <kbd>Ctrl/Cmd</kbd> + arrow                | Moves focus to the first input (previous) or the first empty input (next).      |
| <kbd>Home</kbd> / <kbd>ArrowUp</kbd>       | Moves focus to the first input.                                                 |
| <kbd>End</kbd> / <kbd>ArrowDown</kbd>      | Moves focus to the first empty input (the last when all are filled).            |
| <kbd>Backspace</kbd>                       | Clears the focused slot, or the previous slot when it is empty, and moves back. |
| <kbd>Ctrl/Cmd</kbd> + <kbd>Backspace</kbd> | Clears all inputs and moves to the first.                                       |
| <kbd>Delete</kbd>                          | Clears the focused slot.                                                        |

Backspace and Delete have no effect when the control is read-only. Pasted text fills the slots
from the focused one.

## Examples

### One-Time Password verification

Use `otp` and `groupSize` for a standard 6-digit SMS verification code.

```tsx
import { PinInput } from 'moraine'
import { createSignal, Show } from 'solid-js'

export function OtpExample() {
  const [completedCode, setCompletedCode] = createSignal('')

  return (
    <div class="flex flex-col gap-3">
      <PinInput length={6} groupSize otp onComplete={(code) => setCompletedCode(code)} />
      <Show when={completedCode()}>
        <p class="text-sm text-muted-foreground">Verification code entered: {completedCode()}</p>
      </Show>
    </div>
  )
}
```

### Form integration and validation

Place `PinInput` inside `form.Field` with a validation schema so submission requires every slot to be filled.

```tsx
import { Button, createForm, PinInput } from 'moraine'
import { createSignal } from 'solid-js'
import * as v from 'valibot'

export function FormIntegration() {
  const [submittedCode, setSubmittedCode] = createSignal('')
  const form = createForm({
    schema: v.object({
      code: v.pipe(
        v.string('Verification code is required'),
        v.length(6, 'Verification code must be 6 digits'),
        v.regex(/^\d+$/, 'Verification code must contain digits only'),
      ),
    }),
    initialInput: { code: '' },
    validate: 'submit',
  })

  return (
    <form.Form onSubmit={(output) => setSubmittedCode(output.code)}>
      <div class="max-w-md space-y-4">
        <form.Field
          name="code"
          label="Verification code"
          description="Enter the 6-digit code sent to your device."
          required
        >
          <PinInput length={6} groupSize validationType="number" otp />
        </form.Field>
        <div class="flex gap-3 items-center">
          <Button type="submit" variant="soft" tone="neutral" size="sm">
            Verify
          </Button>
          <p class="text-xs text-muted-foreground">Verified: {submittedCode() || 'none'}</p>
        </div>
      </div>
    </form.Form>
  )
}
```

### Masked PIN for security

Use `mask` to hide the entered characters for sensitive passcodes and PINs.

```tsx
import { Field, PinInput } from 'moraine'
import { createSignal, Show } from 'solid-js'

export function Masked() {
  const [pin, setPin] = createSignal('')

  return (
    <div class="max-w-sm space-y-3">
      <Field
        label="Transaction PIN"
        description="Enter your 4-digit security PIN for confirmation."
      >
        <PinInput validationType="number" length={4} mask onComplete={(val) => setPin(val)} />
      </Field>
      <Show when={pin()}>
        <p class="text-xs text-muted-foreground">PIN entered ({pin().length} digits)</p>
      </Show>
    </div>
  )
}
```

### Alphanumeric recovery key

Use `validationType="alphanumeric"` to accept letters and digits in backup keys and recovery codes.

```tsx
import { Field, PinInput } from 'moraine'
import { createSignal, Show } from 'solid-js'

export function Alphanumeric() {
  const [code, setCode] = createSignal('')

  return (
    <div class="max-w-md space-y-3">
      <Field
        label="Backup Recovery Key"
        description="Enter your 8-character alphanumeric recovery key."
      >
        <PinInput
          validationType="alphanumeric"
          length={8}
          groupSize={4}
          onComplete={(val) => setCode(val)}
        />
      </Field>
      <Show when={code()}>
        <p class="text-xs text-muted-foreground font-mono">Recovery key: {code()}</p>
      </Show>
    </div>
  )
}
```

### Custom separator

Pass `separatorRender` to replace the divider between slot groups. It receives the `index` of the slot it follows.

```tsx
import { PinInput } from 'moraine'
import { createSignal, Show } from 'solid-js'

export function CustomSeparator() {
  const [value, setValue] = createSignal('')

  return (
    <div class="flex flex-col gap-3">
      <PinInput
        length={6}
        groupSize={3}
        separatorRender={() => <span class="text-muted-foreground font-semibold px-1">-</span>}
        onComplete={(val) => setValue(val)}
      />
      <Show when={value()}>
        <p class="text-xs text-muted-foreground">Code: {value()}</p>
      </Show>
    </div>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-complete` | `pin-input`, `pin-input-input` | — |
| `data-disabled` | `pin-input`, `pin-input-input` | Present when the component, slot, or item is disabled. |
| `data-filled` | `pin-input`, `pin-input-input` | — |
| `data-focused` | `pin-input`, `pin-input-input` | Present when the element holds keyboard focus. |
| `data-invalid` | `pin-input`, `pin-input-input` | Present when the field or form has a validation error. |
| `data-readonly` | `pin-input`, `pin-input-input` | Present when the field is in read-only mode. |
| `data-required` | `pin-input`, `pin-input-input` | Present when the field input is required. |

### Props

Props for the PinInput component.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| autofocus | boolean \| undefined | false | Whether to focus the first empty slot after mounting, or the last slot when all are filled.<br>Focus is skipped when the control is disabled, and `autofocusDelay` postpones it. |
| autofocusDelay | number \| undefined | 0 | Delay in milliseconds between mount and focusing. Only used with `autofocus`. |
| autoSubmit | boolean \| undefined | false | Whether to call `requestSubmit()` on the owning form, which runs native validation and<br>fires a `submit` event, right after `onComplete`. The form is found through `form`, the<br>inputs, or the closest ancestor `<form>`; nothing happens without one. |
| defaultValue | string[] \| string \| undefined | — | Initial value for uncontrolled usage, as a joined string or one character per slot. Also<br>the value restored when the owning form is reset. |
| disabled | boolean \| undefined | false | Whether the control is disabled: it cannot be interacted with and sets `aria-disabled`.<br>When omitted, the control inherits `disabled` from the surrounding `Field`; an explicit<br>`false` overrides the `Field`. |
| form | string \| undefined | — | The `id` of the `<form>` the control belongs to, for a control rendered outside that form.<br>It is set on the slot inputs and on the hidden input that submits the joined value under `name`. |
| groupSize | boolean \| number \| readonly number[] \| undefined | — | Group inputs by inserting a separator between groups.<br>Pass `true` to split inputs in half, a number for groups of that size,<br>or an array of consecutive group sizes. |
| id | string \| undefined | — | The ID of the control's main focusable element, which a surrounding `Field` label points to<br>with `for`. A unique ID is generated when omitted. The control's related parts (hidden<br>input, label, description) derive their IDs from it, so keep it unique on the page. |
| inputMode | JSX.HTMLAttributes<HTMLInputElement>['inputMode'] \| undefined | — | The virtual keyboard hint applied to the inputs and hidden input.<br>Overrides the `inputMode` derived from `validationType`. |
| inputRefs | Ref<HTMLInputElement[]> \| undefined | — | Receives the array of the slot `<input>` elements, in order, after mount and whenever<br>`length` changes. It is called with an empty array on cleanup. |
| length | number \| undefined | 5 | The number of single-character inputs, at least 1. Longer values are truncated to it. |
| mask | boolean \| undefined | false | Whether to hide the entered characters by rendering the slots as `type="password"` inputs. |
| name | string \| undefined | — | The name of the control, used for native form submission. When omitted, the control uses<br>the name of its form binding or a string `name` set on the surrounding `Field`. |
| normalizeValue | ((value: string) => string) \| undefined | — | Normalizes a proposed value after `validationType` filtering; the result is<br>filtered again and clamped to `length`. Applied to string `value`/`defaultValue`<br>and to typed, pasted, or autofilled text.<br>Should be idempotent, since it may run on the same value more than once. |
| onBlur | JSX.FocusEventHandlerUnion<HTMLDivElement, FocusEvent> \| undefined | — | Native blur event when focus leaves the pin input group. Calling `preventDefault` skips the<br>`Field` blur notification. |
| onComplete | ((value: string) => void) \| undefined | — | Called with the joined string when every slot is filled. For controlled values it fires once<br>the value is actually applied. Runs before the form is submitted when `autoSubmit` is set. |
| onFocus | JSX.FocusEventHandlerUnion<HTMLDivElement, FocusEvent> \| undefined | — | Native focus event when focus enters the pin input group from outside. Calling<br>`preventDefault` skips the `Field` focus notification. |
| onFocusIn | JSX.FocusEventHandlerUnion<HTMLDivElement, FocusEvent> \| undefined | — | Native focusin event for every slot focus, including moves between slots.<br>Calling `preventDefault` skips `onFocus`. |
| onFocusOut | JSX.FocusEventHandlerUnion<HTMLDivElement, FocusEvent> \| undefined | — | Native focusout event for every slot blur, including moves between slots.<br>Calling `preventDefault` skips `onBlur`. |
| onValueChange | ((value: string[]) => void) \| undefined | — | Called whenever the entered characters change, with an array of `length` entries holding<br>one character per slot and `''` for empty slots. Use `.join('')` for the string. |
| onValueInvalid | ((details: ValueInvalidDetails) => void) \| undefined | — | Called when entered text is refused: a typed, pasted, or autofilled batch containing<br>characters dropped by `validationType` or `normalizeValue` (`reason: 'patternMismatch'`),<br>or a paste with more valid characters than `length` (`reason: 'tooLong'`). Accepted<br>characters from the same input are still applied and reported through `onValueChange`; a<br>paste that breaks both rules calls it once per reason. Does not fire for whitespace and<br>dashes, which are stripped silently. It cannot cancel the input and is unrelated to the<br>native `invalid` event. |
| otp | boolean \| undefined | false | Whether to enable One-Time Password autofill by setting `autocomplete="one-time-code"` on<br>the first slot, and on the hidden input when `name` is set. A received code is spread across the slots. |
| placeholder | string \| undefined | — | Placeholder text shown in empty slots that are not focused, typically one character such as `○`. |
| readOnly | boolean \| undefined | false | Whether the control is read-only: the value is visible and focusable but cannot be changed,<br>and `aria-readonly` is set. When omitted, the control inherits `readOnly` from the<br>surrounding `Field`. |
| ref | Ref<HTMLDivElement> \| undefined | — | Ref callback or variable that receives the root `<div>` container element. |
| required | boolean \| undefined | false | Whether the control is required, which sets `aria-required` (and the native `required`<br>attribute where the control renders a native input). When omitted, the control inherits<br>`required` from the surrounding `Field`. |
| separatorRender | Component<SeparatorRenderProps> \| undefined | — | Component that renders the separator content between groups, replacing the default `•`.<br>It receives the `index` of the input it follows and only appears when `groupSize` creates groups. |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Visual size of the component. |
| translations | Translations \| undefined | — | Localized message overrides for this pin input instance. `input` builds the `aria-label` of<br>each slot from its 1-based `index` and the `length`. |
| validationType | ValidationType \| undefined | 'text' | Which characters a slot accepts: `'number'` digits `0-9`, `'alpha'` letters `a-z` / `A-Z`,<br>`'alphanumeric'` both, `'text'` any non-whitespace character. Rejected characters are dropped<br>and reported to `onValueInvalid`. It also picks the default `inputMode` (`numeric` for<br>`'number'`, `text` otherwise). |
| value | string[] \| string \| undefined | — | Controlled value as a joined string (`'123456'`) or an array with one character per slot<br>(an empty string `''` leaves that slot empty). `undefined` leaves the input uncontrolled. The<br>value is filtered by `validationType` and truncated to `length`; update it from `onValueChange`. |
| variant | 'outline' \| 'subtle' \| 'ghost' \| 'none' \| undefined | 'outline' | Visual treatment of the component. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`groupSize` examples**

```tsx
true // splits in half -> [X][X][X] • [X][X][X]
```

```tsx
3 // groups of 3 -> [X][X][X] • [X][X][X]
```

```tsx
[3, 1, 3] // explicit sizes -> [X][X][X] • [X] • [X][X][X]
```

**`onValueInvalid` example**

```tsx
import { PinInput } from 'moraine'

<PinInput
  validationType="number"
  onValueInvalid={({ value, reason }) => console.warn(reason, value)}
/>
```

**`separatorRender` example**

```tsx
import { PinInput } from 'moraine'

<PinInput length={6} groupSize={3} separatorRender={() => <span>–</span>} />
```

**`translations` example**

```tsx
import { PinInput } from 'moraine'

<PinInput
  length={6}
  translations={{ input: ({ index, length }) => `Digit ${index} of ${length}` }}
/>
```
