Skip to content
// EFFECT DAYS 2026

OTPField unstable

A one-time code field: a row of one-character inputs for a verification code, which move focus as the user types, take a pasted or autofilled code whole, and submit it as one form value.

OTPField is a headless component. It keeps which slot has focus and the slot an input method is composing in, moves focus and selects a slot's text with Commands, and emits Updated, Completed and Rejected. The code itself is the consumer's: it comes in as the value prop.

Anatomy

Part Element
root any element that can contain an <input>, usually a <div>
input <input>, one for each slot

root takes the consumer's builder and returns it, so the consumer goes on chaining and adds the slots with .children(...). input takes { element, index }, the slot's <input> and its place in the code from 0, and returns the builder. An index outside the field's length, or drawn twice, fails the render.

The root adds elements after the consumer's children. First a hidden <span> for each slot, holding its position, such as "2 of 6", which the slot's name points at. Last a visually hidden <input type="text">. It holds the whole code under the name prop, so the form submits one value, carries required and the pattern so the browser can refuse an incomplete code, and takes the browser's autofill. None of them takes up room or counts in a flex or grid gap, but :last-child, :nth-child and a selector such as .otp input do match them. Style the slots by a class of their own.

Anything may sit between the slots, such as a Separator between two groups of three.

Data attributes

On the root and on every slot, present with an empty value or absent:

  • data-disabled, data-readonly and data-required, from the props
  • data-complete: every slot has a character
  • data-filled: on the root, the code isn't empty; on a slot, the slot has a character
  • data-focused: a slot has focus

Keyboard

A key handler on each slot, since no native element gives these:

Key Action
a character fills the slot and moves to the next
Left, Right move one slot
Ctrl or Cmd with Left, Home, Up move to the first slot
Ctrl or Cmd with Right, End, Down move to the first empty slot
Backspace removes the slot's character and moves back, or removes
the previous one from an empty slot
Ctrl or Cmd with Backspace clears the code
Delete removes the slot's character and stays

Removing a character moves the later ones one slot back, so the code has no gaps, and focus never goes past the first empty slot. Only one slot is in the Tab order: the focused one, or else the first empty one. In a right-to-left layout, Left and Right swap. The field follows the nearest DirectionProvider above it or, without one, the root's CSS direction. A key held with Alt does nothing and keeps its default, such as Back on Alt+Left, and so does a navigation key held with Shift, which selects text. A read-only field keeps the navigation keys and drops the editing ones. A disabled field handles none.

Usage

The value is controlled and redacted (Redacted<string>), so the code stays out of message logs, server page state and history. Each edit emits Updated with the code the user asked for, and the slots show it once the consumer passes it back as value. Focus moves on with the edit, and goes back to the first empty slot when the consumer stored fewer characters than were typed. So the consumer's update is where a code is changed on the way in: store Redacted.make(Redacted.value(value).toUpperCase()) to show capitals, or use validationType: "none" and drop the characters a rule of your own rejects. A form's submit event hands the code over as a plain string in fields[name]. Wrap it with Redacted.make before it goes into a message, or read the code from your Model.

The consumer usually answers an edit in the update that handles Updated. If value is another code on the render that follows, the edit was accepted, whatever the consumer made of it. If value is still the same code, the field drops its temporary value and returns focus to the first empty slot, but remembers a complete requested code until the next value change or the next edit: if the next value change stores that exact code, it still completes; a different code or a newer edit discards it. Keys that arrive before the render settles carry on from the code the last edit asked for.

Completed and autoSubmit follow an accepted edit, and read the code the consumer stored. A consumer that declines the edit and later stores an unrelated code gets no completion. autoSubmit submits a form that holds the code, through the form's own validation and its submit handler.

Pasted text fills the slots from the one it was pasted into. Text an input method composes is entered once, when the composition ends.

Name the field for assistive technology. The root is a group: give it aria-labelledby, which field.group does from field.legend, or an aria-label. Or use a <label>, around the first slot or with for pointing at the id prop: it focuses the first slot, and the field finds it when it mounts and names the root by it, giving it an id if it has none. Each slot with no aria-label and no aria-labelledby of its own is then named by the group's name and its position, wherever it is drawn, such as "Verification code 2 of 6". It points aria-labelledby at the group's label, or at a root named by aria-label, which gets an id if it has none, and at the slot's hidden position. The position is in English. For another language, give every slot an aria-label of its own, such as "Chiffre 2 sur 6". A field with no name leaves the slots unnamed.

In a Field, the root takes field.group, each slot's element takes field.member, and the props take disabled: field.disabled. Apply the field's part first, otpField.root(field.group(h.div)), so the slot's own data-filled and data-focused are the ones that show.

Example A six-digit code

import { UiSchema } from "effect/ui"
import { Html, HtmlServer } from "effect/ui/html"
import { OTPField } from "effect/ui/kit"
import { Effect, Redacted, Schema } from "effect"
const VerifyMessage = UiSchema.TaggedEnum({ UpdatedCode: { value: Schema.Redacted(Schema.String) } })
const Verify = Html.component({
name: "Verify",
model: Schema.Struct({ code: Schema.Redacted(Schema.String) }),
message: VerifyMessage
}).make({
init: () => ({ code: Redacted.make("12") }),
update: { UpdatedCode: (_, { value }) => ({ code: value }) },
view: (h, model) =>
OTPField(h, {
props: { value: model.code, length: 6, name: "code" },
onEmit: {
Updated: ({ value }) => VerifyMessage.UpdatedCode({ value }),
Completed: () => undefined,
Rejected: () => undefined
},
view: (otpField) =>
otpField.root(h.div.class("otp").attr("aria-label", "Verification code")).children(
Array.from({ length: otpField.length }, (_, index) =>
otpField.input({ element: h.input.class("slot"), index }))
)
})
})
// Six slots, two of them filled, each named with its position, and one hidden input that submits the code.
const { html } = await Effect.runPromise(HtmlServer.renderToHtml(Verify, {}))
if (html.match(/<input class="slot"/g)?.length !== 6) throw new Error("the field doesn't draw six slots")
if (!html.includes(">2 of 6</span>")) throw new Error("the second slot's position isn't there")
if (html.match(/<input class="slot"[^>]* data-filled/g)?.length !== 2) throw new Error("two slots aren't filled")
if (!/<input [^>]*name="code"[^>]* value="12"/.test(html)) throw new Error("the hidden input doesn't hold the code")
13 exports Since v4.2.0 Source

Components

OTPField

unstable
Since v4.2.0

A headless one-time code field. Call it with the consumer's h, the props, an onEmit for its events, and a view closure that draws the root with otpField.root(h.div) and, inside it, one otpField.input({ element: h.input, index }) for each slot.

Details

The parts also return value, a Redacted<string> of the code the slots show, length, and complete, filled, focused, disabled, readOnly and required as booleans, for markup that depends on them.

The field's own attributes win over the ones the consumer set on the builder before the part, including the ones a state leaves absent:

  • root: role="group", data-disabled, data-readonly, data-required, data-complete, data-filled and data-focused
  • input: the value property, id when the id prop is set, inputmode, autocomplete, autocorrect, spellcheck, enterkeyhint, maxlength, tabindex, form, pattern, readonly, required, disabled, aria-disabled, which it never sets, and the same data attributes as the root, with data-filled for the slot's own character

A part writes them when it is applied, so an attribute the consumer chains after the part is the consumer's to answer for. Two are left to the consumer: a slot's own type is kept, and the field writes password or text only on a slot with none; and a slot's aria-label or aria-labelledby is kept, and the field names only a slot with neither. A root with aria-label and no aria-labelledby keeps its id, and gets one if it has none.

A slot handles input, compositionend, keydown, paste, mousedown, focus and blur on a layer of its own, so the consumer's handlers for them still run. It cancels the keys it handles, every paste, and the mouse press, which would otherwise put a caret beside the character. A key held with Alt, and a navigation key held with Shift, keep their default.

The root has a mount, which reads its CSS direction. The field follows the nearest DirectionProvider above it or, without one, that direction, and swaps Left and Right in a right-to-left layout.

History restore saves nothing of it: after Back, forward or a reload it starts from init.

Signature

declare const OTPField: Headless<{
readonly autoComplete?: string;
readonly autoSubmit?: boolean;
readonly disabled?: boolean;
readonly form?: string;
readonly id?: string;
readonly inputMode?: "decimal" | "search" | "text" | "url" | "none" | "email" | "tel" | "numeric";
readonly length: number;
readonly mask?: boolean;
readonly name?: string;
readonly readOnly?: boolean;
readonly required?: boolean;
readonly validationType?: "none" | "numeric" | "alpha" | "alphanumeric";
readonly value: Redacted<string>;
}, {
readonly _tag: "Updated";
readonly reason: "keyboard" | "input-change" | "input-clear" | "input-paste";
readonly value: Redacted<string>;
} | {
readonly _tag: "Rejected";
readonly reason: "input-change" | "input-paste";
readonly value: Redacted<string>;
} | {
readonly _tag: "Completed";
readonly reason: "input-change" | "input-paste";
readonly value: Redacted<string>;
}, {
complete: boolean;
disabled: boolean;
filled: boolean;
focused: boolean;
input: <B extends PartTarget<"input">>(__namedParameters: {
readonly element: B;
readonly index: number;
}) => ReturnType<B["attr"]> & Pick<Part<"input", [index: number], never>, "~R">;
length: number;
readOnly: boolean;
required: boolean;
root: Part<string, [], never>;
value: Redacted<string>;
}, never, never, never, never, never, never, {
readonly android: boolean;
readonly composed: {
readonly index: number;
readonly text: Redacted<string>;
} | null;
readonly composing: number | null;
readonly edit: {
readonly asked: Redacted<string>;
readonly before: Redacted<string>;
readonly reason: "input-change" | "input-paste" | null;
readonly settled: boolean;
} | null;
readonly edits: number;
readonly focused: boolean;
readonly focusedIndex: number;
readonly label: string | null;
readonly moving: number;
readonly rtl: boolean;
readonly target: number | null;
}, {
readonly _tag: "Settled";
} | {
readonly _tag: "FoundDirection";
readonly rtl: boolean;
} | {
readonly _tag: "PressedKey";
readonly boundary: boolean;
readonly index: number;
readonly key: string;
} | {
readonly _tag: "PastedText";
readonly index: number;
readonly text: Redacted<string>;
} | {
readonly _tag: "UpdatedSlot";
readonly composing: boolean;
readonly index: number;
readonly value: Redacted<string>;
} | {
readonly _tag: "EndedComposition";
readonly index: number;
readonly value: Redacted<string>;
} | {
readonly _tag: "PressedSlot";
readonly index: number;
} | {
readonly _tag: "FocusedSlot";
readonly index: number;
} | {
readonly _tag: "BlurredSlot";
readonly index: number;
} | {
readonly _tag: "FocusedHiddenInput";
} | {
readonly _tag: "UpdatedHiddenInput";
readonly value: Redacted<string>;
} | {
readonly _tag: "DisabledWhileFocused";
} | {
readonly _tag: "CompletedSelectSlot";
} | {
readonly _tag: "CompletedInspectFirstSlot";
readonly android: boolean;
readonly label: string | null;
}, QueryEntries<{}, {}>>

Models

OTPFieldEntryReason

type unstable
Since v4.2.0

How the user entered text.

Signature

type OTPFieldEntryReason = typeof OTPFieldEntryReason.Type

OTPFieldEvents

type unstable
Since v4.2.0

What an OTPField emits.

Signature

type OTPFieldEvents = typeof OTPFieldEvents.Type

OTPFieldInputMode

type unstable
Since v4.2.0

The virtual keyboard a one-time code field asks for.

Signature

type OTPFieldInputMode = typeof OTPFieldInputMode.Type

OTPFieldProps

type unstable
Since v4.2.0

The props of an OTPField.

Signature

type OTPFieldProps = typeof OTPFieldProps.Type
Since v4.2.0

How the user changed the code.

Signature

type OTPFieldUpdateReason = typeof OTPFieldUpdateReason.Type
Since v4.2.0

Which characters a one-time code field accepts.

Signature

type OTPFieldValidationType = typeof OTPFieldValidationType.Type

Schemas

Since v4.2.0

How the user entered text: "input-change" for typing, an input method or autofill, and "input-paste" for a paste.

Signature

declare const OTPFieldEntryReason: Literals<readonly ["input-change", "input-paste"]>
Since v4.2.0

What a one-time code field emits.

Details

  • Updated: asks for the code in value. Store value and pass it back as the value prop, changed if need be, such as in upper case. Until then the slots go on showing the old code.
  • Completed: the consumer answered text the user typed or pasted by storing a code that fills every slot. value is the stored code, so a consumer that synchronously changes or shortens what it stores gets the code it kept, or no event. If value doesn't change right away, the field still completes if the next value change stores the exact complete code it asked for before another edit arrives; an unrelated code or a newer edit discards it. A complete code pasted over the same code reports it again. Backspace and Delete never complete a code.
  • Rejected: the text the user typed or pasted held characters the field dropped, or more characters than the field has slots. value is that text as entered. The accepted part, if any, is reported by Updated.

Every value is a Redacted<string>.

Signature

declare const OTPFieldEvents: TaggedEnum<{
Completed: TaggedStruct<"Completed", {
readonly reason: Literals<readonly ["input-change", "input-paste"]>;
readonly value: Redacted<String>;
}>;
Rejected: TaggedStruct<"Rejected", {
readonly reason: Literals<readonly ["input-change", "input-paste"]>;
readonly value: Redacted<String>;
}>;
Updated: TaggedStruct<"Updated", {
readonly reason: Literals<readonly ["input-change", "input-clear", "input-paste", "keyboard"]>;
readonly value: Redacted<String>;
}>;
}>
Since v4.2.0

The virtual keyboard a one-time code field asks for, as the inputmode attribute names them.

Signature

declare const OTPFieldInputMode: Literals<readonly ["none", "text", "tel", "url", "email", "numeric", "decimal", "search"]>
Since v4.2.0

Props for the state of an OTPField.

Details

  • value: the code, a Redacted<string>. The slots show it with whitespace and the characters validationType rejects removed, cut to length.
  • length: the number of slots, a positive whole number.
  • id: the first slot's id. The others get id-2, id-3 and so on, so a <label for> focuses the first slot. Left out, each slot keeps the id the consumer gave it.
  • validationType: "numeric" by default, "alpha", "alphanumeric", or "none" to accept any character and leave the rule to the consumer's update.
  • mask: draws each slot as a password input, unless the slot has a type of its own.
  • inputMode: the virtual keyboard. By default "numeric" for a numeric field, "text" for letters, and none for "none".
  • autoComplete: the autocomplete of the first slot and the hidden input, "one-time-code" by default. The other slots get "off".
  • autoSubmit: submits the form the field belongs to once the stored code is complete.
  • disabled: disables every slot and the hidden input, so the field takes no focus, reports nothing and submits nothing.
  • readOnly: keeps focus and the navigation keys, and drops every edit.
  • required: the form doesn't submit while the code is empty.
  • name: the name the form submits the code under.
  • form: the id of the form the field belongs to, when it isn't inside it.

Signature

declare const OTPFieldProps: Struct<{
readonly autoComplete: optional<String>;
readonly autoSubmit: optional<Boolean>;
readonly disabled: optional<Boolean>;
readonly form: optional<String>;
readonly id: optional<String>;
readonly inputMode: optional<Literals<readonly ["none", "text", "tel", "url", "email", "numeric", "decimal", "search"]>>;
readonly length: Number;
readonly mask: optional<Boolean>;
readonly name: optional<String>;
readonly readOnly: optional<Boolean>;
readonly required: optional<Boolean>;
readonly validationType: optional<Literals<readonly ["numeric", "alpha", "alphanumeric", "none"]>>;
readonly value: Redacted<String>;
}>
Since v4.2.0

How the user changed the code: "input-change" for typing, an input method or autofill, "input-clear" for emptying a slot, "input-paste" for a paste, and "keyboard" for Backspace and Delete.

Signature

declare const OTPFieldUpdateReason: Literals<readonly ["input-change", "input-clear", "input-paste", "keyboard"]>

Which characters a one-time code field accepts: digits, letters, both, or anything that isn't whitespace.

Signature

declare const OTPFieldValidationType: Literals<readonly ["numeric", "alpha", "alphanumeric", "none"]>