> Native Solid 2 fork. Original documentation and designs © WorkOS; historical posts retain their original context.

# One-Time Password Field

A group of single-character text inputs to handle one-time password verification.

## Features

- Keyboard navigation mimicking the behavior of a single input field

- Overriding values on paste

- Password manager autofill support

- Input validation for numeric and alphanumeric values

- Auto-submit on completion

- Hidden input to provide a single value to form data

## Anatomy

Import all parts and piece them together.

```jsx
import { unstable_OneTimePasswordField as OneTimePasswordField } from "@radix-solid/primitives";

export default () => <OneTimePasswordField.Root>

		{/* one Input for each character of the value */}

		<OneTimePasswordField.Input />

		{/* single HiddenInput to store the full value */}

		<OneTimePasswordField.HiddenInput />

	</OneTimePasswordField.Root>;
```

## API Reference

### Root

Contains all the parts of a one-time password field.

| Prop                                                                                                                                                                                                                                                                    | Type       | Default         |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details.                                                                                                 | `boolean`  | `false`         |
| `autoComplete`Specifies what—if any—permission the user agent has to provide automated assistance in filling out form field values, as well as guidance to the browser as to the type of information expected in the field.                                             | `enum`     | `one-time-code` |
| `autoFocus`Whether or not the first fillable input should be focused on page-load.                                                                                                                                                                                      | `boolean`  | —               |
| `value`The controlled value of the field. Must be used in conjunction with `onValueChange`.                                                                                                                                                                             | `string`   | —               |
| `defaultValue`The value of the field when initially rendered. Use when you do not need to control the state of the field.                                                                                                                                               | `string`   | —               |
| `onValueChange`Event handler called when the value of the field changes.                                                                                                                                                                                                | `function` | —               |
| `autoSubmit`Whether the component should attempt to automatically submit when all fields are filled. If the field is associated with an HTML `form` element, the form's `requestSubmit` method will be called.                                                          | `boolean`  | `false`         |
| `onAutoSubmit`When the `autoSubmit` prop is set to `true`, this callback will be fired before attempting to submit the associated form. It will be called whether or not a form is located, or if submission is not allowed. No-op when `autoSubmit` is set to `false`. | `function` | —               |
| `disabled`Whether or not the the field's input elements are disabled.                                                                                                                                                                                                   | `boolean`  | `false`         |
| `dir`The reading direction of the field when applicable. If omitted, assumes LTR (left-to-right) reading mode.                                                                                                                                                          | `enum`     | `"ltr"`         |
| `orientation`The vertical orientation of the input elements.                                                                                                                                                                                                            | `enum`     | `"vertical"`    |
| `form`A string specifying the `form` element with which the input is associated. This string's value, if present, must match the ID of a `form` element in the same document.                                                                                           | `string`   | —               |
| `name`A string specifying a name for the input control. This name is submitted along with the control's value when the form data is submitted.                                                                                                                          | `string`   | —               |
| `placeholder`Defines the text displayed in a form control when the control has no value. Split into single-character placeholders for each Input rendered.                                                                                                              | `string`   | —               |
| `readOnly`Whether or not the input elements can be updated by the user.                                                                                                                                                                                                 | `boolean`  | `false`         |
| `sanitizeValue`Function for custom sanitization when `validationType` is set to `"none"`. This function will be called before updating values in response to user interactions.                                                                                         | `function` | —               |
| `type`The input type of the field's input elements.                                                                                                                                                                                                                     | `enum`     | `"text"`        |
| `validationType`Specifies the type of input validation to be used.                                                                                                                                                                                                      | `enum`     | `"numeric"`     |

| Data attribute       | Values                       |
| -------------------- | ---------------------------- |
| `[data-orientation]` | `"vertical" \| "horizontal"` |

### Input

Renders a text input representing a single character in the value.

| Prop                                                                                                                                                                    | Type      | Default |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details. | `boolean` | `false` |

| Data attribute | Values                                                                                   |
| -------------- | ---------------------------------------------------------------------------------------- |
| `[data-index]` | The index corresponding with the index of the character relative to the root field value |

### HiddenInput

| Prop                                                                                                                                                                    | Type      | Default |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ------- |
| `asChild`Render through a single-target factory, merging props and behavior with the chosen host. Read our [Composition](../guides/composition) guide for more details. | `boolean` | `false` |

## Examples

### Basic usage

```jsx
// This will render a field with 6 inputs, for use with

// 6-character passwords. Render an Input component for

// each character of accepted password's length.

<OneTimePasswordField.Root>

	<OneTimePasswordField.Input />

	<OneTimePasswordField.Input />

	<OneTimePasswordField.Input />

	<OneTimePasswordField.Input />

	<OneTimePasswordField.Input />

	<OneTimePasswordField.Input />

	<OneTimePasswordField.HiddenInput />

</OneTimePasswordField.Root>;
```

### Segmented controls

The `Root` component accepts arbitrary children, so rendering a visually segmented list is as simple as rendering separators between inputs. We recommend hiding decorative elements from assistive tech with `aria-hidden` and avoid rendering other meaningful content within `Root` since each child element is expected to belong to the parent with the `group` role.

```jsx
import { Separator } from "@radix-solid/primitives";

<>

<OneTimePasswordField.Root>

	<OneTimePasswordField.Input />

	<Separator.Root aria-hidden="true" />

	<OneTimePasswordField.Input />

	<Separator.Root aria-hidden="true" />

	<OneTimePasswordField.Input />

	<Separator.Root aria-hidden="true" />

	<OneTimePasswordField.Input />

	<OneTimePasswordField.HiddenInput />

</OneTimePasswordField.Root>

</>;
```

### Auto-submit form when password is entered

Use the `autoSubmit` prop to submit an associated form when all inputs are filled.

```tsx
import type { JSX } from "@solidjs/web";

function Verify(p: { validCode: string }) {

  const PASSWORD_LENGTH = 6;

  const handleSubmit: JSX.EventHandler<HTMLFormElement, SubmitEvent> = event => {

    event.preventDefault();

    const formData = new FormData(event.currentTarget);

    if (formData.get("otp") === p.validCode) {

      window.location.assign("/authenticated");

    } else {

      window.alert("Invalid code");

    }

  }

  return <form onSubmit={handleSubmit}>

			<OneTimePasswordField.Root name="otp" autoSubmit>

				{Array.from({ length: PASSWORD_LENGTH }, () => <OneTimePasswordField.Input />)}

				{/* HiddenInput is required for the form to have data associated with the field */}

				<OneTimePasswordField.HiddenInput />

			</OneTimePasswordField.Root>

			<button>Submit</button>

		</form>;

}
```

### Controlled value

```tsx
import { createSignal } from "solid-js";

function Verify(p: { validCode: string }) {

  const [value, setValue] = createSignal("");

  const PASSWORD_LENGTH = 6;

  function handleSubmit() {

    if (value() === p.validCode) {

      window.location.assign("/authenticated");

    } else {

      window.alert("Invalid code");

    }

  }

  return <OneTimePasswordField.Root autoSubmit value={value()} onAutoSubmit={handleSubmit} onValueChange={setValue}>

			{Array.from({ length: PASSWORD_LENGTH }, () => <OneTimePasswordField.Input />)}

		</OneTimePasswordField.Root>;

}
```

## Accessibility

At the time of writing, there is no singular established pattern in WCAG guidelines for implementing one-time password fields as separate inputs. The behavior aims to get as close as possible to having the field act as a single input, with a few exceptions to match user expectations based on our initial research, testing, and gathering feedback.

This component is implemented as `input` elements within a container with a role of `group` to indicate that child inputs are related. Inputs can be navigated and focused using direction keys, and typing input will move focus to the next input until the last input is reached.

Pasting a value into the field will replace the contents of all inputs, regardless of the currently focused input. Based on our research this seems to align with most user expectations, where values are often pasted from password-managers or an email.

### Keyboard Interactions

| Key                   | Description                                                                                    |
| --------------------- | ---------------------------------------------------------------------------------------------- |
| `Enter`               | Attempts to submit an associated `form` if one is found                                        |
| `Tab`                 | Moves focus to the next focusable element outside of the `Root`                                |
| `Shift + Tab`         | Moves focus to the previous focusable element outside of the `Root`                            |
| `ArrowDown`           | Moves focus to the next `Input` when `orientation` is `vertical`.                              |
| `ArrowUp`             | Moves focus to the previous `Input` when `orientation` is `vertical`.                          |
| `ArrowRight`          | Moves focus to the next `Input` when `orientation` is `horizontal`.                            |
| `ArrowLeft`           | Moves focus to the previous `Input` when `orientation` is `horizontal`.                        |
| `Home`                | Moves focus to the first `Input`.                                                              |
| `End`                 | Moves focus to the last `Input`.                                                               |
| `Delete`              | Removes the character in the currently focused `Input` and shifts later values back            |
| `Backspace`           | Removes the character in the currently focused `Input` and moves focus to the previous `Input` |
| `Command + Backspace` | Clears the value of all `Input` elements                                                       |
