Input code
Input code is a form field for a short code split into one box per
character, such as a verification code received by email or text
message, or a PIN. Typing a character fills a box and moves to the next
one, a pasted or autofilled code spreads across every box at once, and
filling the last box completes the code: it is validated right away,
fires euncomplete, and can submit its form on its own.
Dependencies
When to use
Reach for an input code when the user copies a short, fixed-length code from somewhere else: a sign-up or sign-in verification code, a two-factor authentication code, a PIN, a pairing code shown on another device. One box per character shows at a glance how many are expected and how many are left. For a password or any value of free length, see Alternatives below.
Install & usage
npm install @eunomia/elements
import "@eunomia/elements/input-code.js";
<eun-input-code name="code" label="Verification code"></eun-input-code>
Importing the file registers <eun-input-code> as a custom element, with
no further setup needed. It works with any framework, or none, since it's
a standard web component.
npm install @eunomia/elements
<script type="module">
import "@eunomia/elements/input-code.js";
document
.querySelector("eun-input-code")
.addEventListener("euncomplete", (event) => console.log(event.value));
</script>
<eun-input-code name="code" label="Verification code"></eun-input-code>
npm install @eunomia/elements
import "@eunomia/elements/input-code.js";
function VerificationCodeField() {
return <eun-input-code name="code" label="Verification code" />;
}
npm install @eunomia/elements
"use client";
import "@eunomia/elements/input-code.js";
export function VerificationCodeField() {
return <eun-input-code name="code" label="Verification code" />;
}
npm install @eunomia/elements
<script setup>
import "@eunomia/elements/input-code.js";
</script>
<template>
<eun-input-code name="code" label="Verification code" />
</template>
npm install @eunomia/elements
import { CUSTOM_ELEMENTS_SCHEMA, Component } from "@angular/core";
import "@eunomia/elements/input-code.js";
@Component({
selector: "app-verification-code-field",
template: `
<eun-input-code name="code" label="Verification code"></eun-input-code>
`,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class VerificationCodeFieldComponent {}
Alternatives
| You want… | Prefers |
|---|---|
| A password, or any secret of free length | eun-input |
| A value of free length in a known format, such as a reference number | eun-input |
| A phone number with its country code | eun-input-phone |
Guidance
- Say where the code was sent, and how many characters it has, in
instructions - Keep the default
autocomplete="one-time-code", so the browser can offer a code received by text message - Check the code on
euncomplete, and show a wrong or expired code througherror - Offer a way to get a new code next to the field, such as a "Resend code" link
- Use
maskedfor a PIN or a secret code, withrevealableso the user can check what they typed
- Using an input code for a value whose length varies: see Alternatives above
- Masking a one-time code that is only valid for a few minutes, which only makes it harder to copy
- Clearing the boxes on a wrong code without saying why: set
errorinstead - Overriding colors with inline styles instead of the
--field-*and--input-code-*CSS variables
Live testing
Properties
InputCode <eun-input-code>
Attributes
| Name | Type | Default | Description |
|---|---|---|---|
| reveal-last | boolean | false | Whether the last character typed in a masked code stays visible for a moment before it's hidden, as on a phone keyboard. It's hidden as soon as the next one is typed |
| separators | number[] | 'middle' | — | Where dashes split the boxes: a list of box positions to put one after, such as [3] or [2, 4], or 'middle' for one halfway. Purely visual, the value never holds them |
| auto-submit | boolean | false | Whether the owning form is submitted as soon as the code is complete and valid |
| default-value | string | — | The default value applied when the field connects, and restored on form reset |
| show-code-label | string | — | The accessible label of the eye button while the code is hidden. Defaults to the localized string for the current locale (English: "Show code") |
| hide-code-label | string | — | The accessible label of the eye button while the code is shown. Defaults to the localized string for the current locale (English: "Hide code") |
| length | number | 6 | The number of boxes, from 4 to 8. A value outside that range is clamped to it |
| type | 'numeric' | 'alphanumeric' | 'numeric' | The characters accepted: digits only, or digits and Latin letters |
| placeholder | string | — | Shown in every empty box, such as "-" or "•". A placeholder with exactly one character per box is spread across them instead, one character each |
| masked | boolean | false | Whether the characters are hidden behind dots, as in a password field |
| revealable | boolean | false | Whether an eye button lets the user show and hide a masked code. Only shown while masked is set |
| autocomplete | string | 'one-time-code' | The native autocomplete attribute of the first box, which lets the browser fill a code received by text message |
| locale | string | undefined | — | The locale used to resolve dictionary, and (on components that also format dates/times) `Intl`/`toLocaleDateString` output. Defaults to the shared default set via `setDefaultLocale()`, itself defaulting to `"en"`. |
| size | 'xs' | 's' | 'm' | 'l' | 'xl' | 'm' | The box size. A box is as tall as a field and a button of the same size |
| appearance | 'outline' | 'flat' | 'underline' | 'outline' | How each box is drawn: a bordered box, a muted background with no border, or a bottom border only |
| label | string | — | The title label of the field, rendered through the label component. It names the group of boxes |
| instructions | string | — | Instructions displayed below the label |
| required | boolean | false | Whether the field is required |
| hide-label | boolean | false | Whether the label is visually hidden. It still gives the field its accessible name, and the instructions stay visible |
| readonly | boolean | false | Whether the field is read only |
| name | string | — | The field name |
| hint | string | undefined | — | A hint shown under the field, such as format guidance. The error messages take its place while they show. |
| hide-error | boolean | false | Whether the errors are hidden. The hint stays visible |
| invalid | boolean | false | Shows the field as invalid without any message, for an error displayed elsewhere |
| controlled | boolean | false | Opts this field out of the native reset algorithm's value wipe: when `true`, `formResetCallback` leaves `value`/`checked` untouched. Exists for consumers who drive `value` as a controlled React prop (or equivalent in another framework): a browser-native `form.reset()` cannot be observed by React's reconciler unless a prop actually changes, so a native input only "survives" a stray reset (e.g. the unconditional one `useActionState` triggers via `requestFormReset` on every `<form action={fn}>` submission, success or not) because react-dom force-resyncs its `.value` on every commit — a defense custom elements don't get. Setting `controlled` makes the field's own app state the sole source of truth for `value`: the app decides when to clear it, the same way it already decides what to display it as. |
| value | string | — | The code typed so far, without any placeholder |
| disabled | boolean | false | Whether the field is disabled |
| validators | Array<Validators<string>> | — | The list of validation rules applied to the code |
| error | string | — | An error computed outside the field, by the form or by the server, such as a wrong code. While set, the field is invalid and shows this message right away |
Import the exact TypeScript type behind any property above, see
Properties
JS-only — no matching HTML attribute, set these from a script or a template binding.
| Name | Type | Default | Description |
|---|---|---|---|
| boxCount | number | — | The number of boxes actually rendered: length, rounded and clamped to the supported range. |
| separatorPositions | Set<number> | — | The box positions a dash is drawn after, from separators, kept only when they fall between two boxes. |
| complete | boolean | — | Whether every box holds a character. |
| dirty | boolean | false | Whether the value has changed since the field connected (or since the last reset). Derived from `eunchange`, the event every field's own user-interaction handler already dispatches (and only that: setting `.value`/`.defaultValue` from outside, as a controlled React field does on every render, never dispatches it), so a controlled field stays pristine across ordinary re-renders and only turns dirty from genuine user input. |
| touched | boolean | false | Whether the field has lost focus at least once since it connected (or since the last reset). |
| pristine | boolean | — | Whether the value hasn't changed since the field connected (or since the last reset). The inverse of dirty. |
| untouched | boolean | — | Whether the field hasn't lost focus yet since it connected (or since the last reset). The inverse of touched. |
| form | — | Reference to the native form element this control belongs to. | |
| errorMessages | string[] | [] | List of validation error messages collected from validators. |
| validity | — | Current validity state of the element. | |
| validationMessage | — | Current validation message or messages. | |
| willValidate | — | Whether the element will be validated. |
Methods
| Name | Returns | Description |
|---|---|---|
| focus() | void | Focuses the first box to fill, or the last box once the code is complete. |
| clear() | void | Empties every box and notifies consumers. |
| checkValidity(dataToCheck: U) | Runs all validation rules and updates internal validity. | |
| reportValidity(valToCheck: boolean | U) | Reports validity and shows native validation UI. |
Events
| Name | Type | Description |
|---|---|---|
| eunchange | ChangeEvent | Fired on every change of the code |
| euncomplete | CompleteEvent | Fired when the user fills the last empty box. Cancelable: preventing it stops auto-submit |
Every event above follows the same naming convention, covered in
CSS custom properties
| Name | Description |
|---|---|
| --input-code-box-size | Sets the width and height of each box. Defaults to the height of a field of the same size |
| --input-code-gap | Sets the space between two boxes |
| --input-code-font-size | Sets the font size of the characters |
| --input-code-separator-color | Sets the color of the dashes splitting the boxes |
| --input-code-separator-width | Sets the width of the dashes splitting the boxes. Defaults to 8px |
| --field-background | Sets the background color of the boxes, the surface color by default for the outline appearance |
| --field-border-color | Sets the border color of the boxes |
| --field-border-size | Sets the width of the box borders. Defaults to 1.5px |
| --field-border-color-hover | Sets the border color on hover |
| --field-border-color-focus | Sets the border color on focus |
| --field-border-radius | Sets the corner radius of the boxes |
| --field-text-color | Sets the text color of the boxes |
| --field-placeholder-color | Sets the color of the placeholder |
| --field-icon-color | Sets the color of the eye button |
| --field-error-color | Sets the color of the error message and of the box borders while invalid |
| --field-hint-color | Sets the color of the hint message |
| --field-focus-outline-color | Sets the color of the focus outline |
| --field-label-font-size | Sets the font size of the label |
| --field-message-font-size | Sets the font size of the hint, error messages and instructions |
Basic
<eun-input-code name="code" label="Verification code"></eun-input-code>
Code format
Length
length sets the number of boxes, from 4 to 8, with 6 by default. A
value outside that range is brought back to the nearest bound.
<eun-input-code label="4 boxes" length="4"></eun-input-code>
<eun-input-code label="8 boxes" length="8"></eun-input-code>
Digits or letters
By default, type="numeric" only accepts digits, and opens the numeric
keypad on a touch screen. type="alphanumeric" also accepts Latin
letters, kept in the case they were typed in. Any other character typed
or pasted is ignored: the box stays as it was.
<eun-input-code label="Pairing code" type="alphanumeric" length="8">
</eun-input-code>
Placeholder
No placeholder by default. Any placeholder is shown in every empty box,
such as a dash or a dot. A placeholder with exactly one character per box
is spread across the boxes instead, one character each, for a sample
code.
<eun-input-code label="Dash" placeholder="-"></eun-input-code>
<eun-input-code label="Dot" placeholder="•"></eun-input-code>
<eun-input-code label="Sample code" length="4" placeholder="0000">
</eun-input-code>
Separators
separators splits the boxes with dashes, to make a long code easier to
read and to copy. Give it the box positions to put a dash after, as a
comma-separated list, as many as needed: separators="3" turns 6 boxes
into 3 and 3, separators="2,4" into three pairs. separators="middle"
puts a single dash halfway, whatever the length (after the 2nd box of a
5-box code). Positions outside the boxes are ignored.
The dashes are only drawn: the value never holds them, the arrow keys skip them, and screen readers don't announce them. A pasted code containing dashes still fills the boxes, since they are ignored.
<eun-input-code label="Middle" separators="middle"></eun-input-code>
<eun-input-code label="Pairs" separators="2,4"></eun-input-code>
<eun-input-code
label="Licence key"
type="alphanumeric"
length="8"
separators="4"
></eun-input-code>
From JavaScript, set the property to an array of positions, or to
"middle":
document.querySelector("eun-input-code").separators = [2, 4];
Masked and revealable
masked hides the characters behind dots, as in a password field.
Add revealable to show an eye button after the boxes, which shows and
hides the code. The eye is only shown while the code is masked.
<eun-input-code label="PIN" length="4" masked></eun-input-code>
<eun-input-code label="PIN" length="4" masked revealable></eun-input-code>
Showing the last character typed
Add reveal-last to a masked code to show each character in clear for a
moment as it's typed, then hide it, as a phone keyboard does in a
password field. The user can check every character without revealing
the whole code. The character is hidden as soon as the next one is
typed, after 1.5 seconds, when a character is erased, or when focus
leaves the code. A pasted or autofilled code is never shown.
<eun-input-code label="PIN" length="4" masked reveal-last></eun-input-code>
Completion
Filling the last empty box completes the code. The field then checks its
validity straight away, showing its error without waiting for focus to
leave, and fires euncomplete, carrying the code as event.value. That's
the moment to verify it, and to report a wrong code through error, which
outlines every box in red. Clear error again on the next eunchange.
Try 123456 below, then any other code.
<eun-input-code id="code" label="Verification code"></eun-input-code>
const field = document.querySelector("#code");
field.addEventListener("euncomplete", async (event) => {
const ok = await verifyCode(event.value);
field.error = ok ? undefined : "This code is incorrect";
});
field.addEventListener("eunchange", () => {
field.error = undefined;
});
import { useEffect, useRef, useState } from "react";
function VerificationCodeField() {
const fieldRef = useRef(null);
const [error, setError] = useState();
useEffect(() => {
const field = fieldRef.current;
const onComplete = async (event) => {
const ok = await verifyCode(event.value);
setError(ok ? undefined : "This code is incorrect");
};
const onChange = () => setError(undefined);
field.addEventListener("euncomplete", onComplete);
field.addEventListener("eunchange", onChange);
return () => {
field.removeEventListener("euncomplete", onComplete);
field.removeEventListener("eunchange", onChange);
};
}, []);
return (
<eun-input-code ref={fieldRef} label="Verification code" error={error} />
);
}
<script setup>
import { ref } from "vue";
const error = ref();
const onComplete = async (event) => {
const ok = await verifyCode(event.value);
error.value = ok ? undefined : "This code is incorrect";
};
</script>
<template>
<eun-input-code
label="Verification code"
:error="error"
@euncomplete="onComplete"
@eunchange="error = undefined"
></eun-input-code>
</template>
import { CUSTOM_ELEMENTS_SCHEMA, Component } from "@angular/core";
@Component({
selector: "app-verification-code-field",
template: `
<eun-input-code
label="Verification code"
[error]="error"
(euncomplete)="onComplete($event)"
(eunchange)="error = undefined"
></eun-input-code>
`,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class VerificationCodeFieldComponent {
error?: string;
async onComplete(event: Event & { value: string }) {
const ok = await verifyCode(event.value);
this.error = ok ? undefined : "This code is incorrect";
}
}
Submitting on completion
Set auto-submit to submit the owning form as soon as the code is
complete and valid, so the user never has to reach the submit button.
The form goes through its usual submission, including the validation of
its other fields. Call preventDefault() on euncomplete to skip it for
that code, for instance while a request is already running.
Not submitted yet
<form>
<eun-input-code name="code" label="Verification code" length="4" auto-submit>
</eun-input-code>
<eun-button type="submit">Verify</eun-button>
</form>
Display
Sizes
size goes from xs to xl, with m by default. Each box is a square
as tall as a field and a button of the same size, so the code lines up
with the actions next to it.
<eun-input-code label="Large" size="l" length="4"></eun-input-code>
Appearance
The same outline (default), flat and underline appearances as
eun-input, applied to every box.
<eun-input-code
label="Outline"
length="4"
appearance="outline"
></eun-input-code>
<eun-input-code label="Flat" length="4" appearance="flat"></eun-input-code>
<eun-input-code
label="Underline"
length="4"
appearance="underline"
></eun-input-code>
States and validation
Disabled and readonly
<eun-input-code label="Disabled" length="4" value="1234" disabled>
</eun-input-code>
<eun-input-code label="Readonly" length="4" value="1234" readonly>
</eun-input-code>
Required and incomplete
A code missing some characters is always invalid, with a message saying
how many are expected, whether or not the field is required. An empty
code is only invalid when required. Like every Eunomia field, the error
only shows once the user leaves the field, completes the code, or submits
the form.
<eun-input-code
label="Verification code"
length="6"
required
hint="Check your inbox"
></eun-input-code>
Error
Set error for an error found outside the field, such as a wrong or
expired code checked by the server: every box is outlined in red, and the
message replaces the hint. invalid shows the red outline alone, for a
message displayed elsewhere. Rules of your own go through validators,
the same way as on eun-input.
<eun-input-code
label="Verification code"
value="482913"
error="This code has expired. Request a new one"
></eun-input-code>
Forms
Like every other Eunomia field, eun-input-code is a real
name, takes part in the form's validation, and restores its
default-value on reset. Pressing Enter in a box submits the form, as in
a native text field.
{}
<form id="my-form">
<eun-input-code name="code" label="Verification code" required>
</eun-input-code>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
Custom
The boxes read the same --field-* CSS variables as every text field,
so a theme applied to the fields applies to them too. Three
--input-code-* variables cover what is specific to the boxes. The full
list is in the API tab.
<eun-input-code class="custom-code" label="Custom" length="4"></eun-input-code>
.custom-code {
--input-code-box-size: 56px;
--input-code-gap: 12px;
--input-code-font-size: 24px;
--field-border-radius: 12px;
--field-border-color-focus: #be185d;
--field-focus-outline-color: #be185d;
}
| Variable | Sets |
|---|---|
--input-code-box-size |
Sets the width and height of each box |
--input-code-gap |
Sets the space between two boxes |
--input-code-separator-color |
Sets the color of the dashes splitting the boxes |
--input-code-font-size |
Sets the font size of the characters |
--field-background |
Sets the background color of the boxes |
--field-border-color |
Sets the border color of the boxes |
--field-border-color-hover |
Sets the border color on hover |
--field-border-color-focus |
Sets the border color on focus |
--field-border-radius |
Sets the corner radius of the boxes |
--field-text-color |
Sets the text color of the boxes |
--field-placeholder-color |
Sets the color of the placeholder |
--field-error-color |
Sets the color of the error message and of the box borders while invalid |
--field-focus-outline-color |
Sets the color of the focus outline |
Keyboard and focus
Keyboard interactions
The boxes form a single tab stop. When focus is on a box:
| Key | Action |
|---|---|
Tab / Shift+Tab |
Moves focus in and out of the code, landing on the first empty box (single tab stop) |
| Any accepted character | Fills the box, replacing its character if it had one, and moves to the next box |
ArrowRight |
Moves to the next box, up to the first empty one |
ArrowLeft |
Moves to the previous box |
Home |
Moves to the first box |
End |
Moves to the first empty box, or to the last box once the code is complete |
Backspace |
Empties the box, or, when it's already empty, empties the previous box and moves to it |
Delete |
Empties the box |
Ctrl+V / Cmd+V |
Spreads the pasted code across the boxes, ignoring spaces and dashes |
Enter |
Submits the closest ancestor <form>, as a native text field does |
In a right-to-left page, ArrowLeft and ArrowRight swap, following the
reading direction. The eye button of a revealable code comes right after
the boxes in the tab order.
Where focus goes
The code is always filled in order, without gaps:
- Tabbing into the field, clicking its label, calling
focus()on it, or clicking any box while the code is incomplete all bring the cursor to the first empty box - Once the code is complete, clicking a box focuses that box, to correct a single character. The arrow keys reach any filled box at any time
- Emptying a box in the middle moves the following characters back by one box, rather than leaving a hole
Semantics and screen readers
Aria attributes
- The boxes are wrapped in a
role="group"named bylabel, so a screen reader announces the field's name once, when focus enters it - Each box is a native text field named after its position, "Digit 1 of 6" (or "Character 1 of 6" for an alphanumeric code), in the field's locale
aria-invalid="true"is set on every box while the field shows its error, so each box is announced as invalidaria-required="true"is set on every box whilerequiredaria-describedby="description"links every box to the hint or the error message, whenever one is shown- The dashes of
separatorscarryaria-hidden="true": they're only drawn, so nothing is announced between two boxes - The eye button carries
aria-pressed, and its label follows its state: "Show code" or "Hide code" (show-code-labelandhide-code-label)
Label accessibility
Always set label, or slot equivalent content into the label slot: it
names the group of boxes. Use instructions to say where the code was
sent and how many characters it has, since the boxes alone don't tell a
screen reader user before they reach them.
Autofill and input methods
The first box carries autocomplete="one-time-code", so Safari and
Chrome on mobile offer a code received by text message, filling every box
at once. A numeric code sets inputmode="numeric", which opens the
numeric keypad on a touch screen. Autocorrection, spellcheck and
automatic capitalization are turned off on every box.
Field states
Disabled vs. readonly
disabled takes every box out of the tab order and out of the form
submission. readonly keeps the boxes focusable and the code submitted,
and lets the user move between them, without changing the code. Prefer
readonly whenever the code is still useful to read.
Error / validation state
An incomplete code reports tooShort, and an empty required code
valueMissing, through the same checkValidity() and validity surface
as every custom validators error. The message replaces the hint in the
same #description region, linked to every box. Completing the code
reveals its errors right away, so a wrong code is announced as soon as
the last character is typed.
Server-side rendering
The label, the instructions and the boxes are drawn inside the input
code's shadow root, so a server-rendered input code takes no space until
the element upgrades, then pushes the content below it. Link
input-code-ssr.css in the page's <head> to draw them from the first
paint:
<link
rel="stylesheet"
href="node_modules/@eunomia/elements/dist/ssr/input-code-ssr.css"
/>
A bundler that resolves package exports can reach it as
@eunomia/elements/input-code-ssr.css. It reads label, required,
instructions, length, separators, size, appearance, masked,
revealable, disabled, readonly and the --input-code-* and
--field-* custom properties, written in the server-rendered markup. The
label and the instructions take their final height, and the boxes, the
dashes and the room of the eye button their final place. The characters,
the placeholders, the eye button and the messages show with the upgrade.
Reference links
WAI-ARIA Authoring Practices: Grouping Labels WCAG 2.2: Accessible Authentication (Minimum) WHATWG HTML: The one-time-code autofill field Apple: Enabling password AutoFill on an HTML input element