Accessible form field web component with label, input, validation timing, custom error messages, and error summaries. Progressive enhancement from CSS-only validation to full JS coordination.
Attributes
| Attribute |
Values |
Default |
Description |
data-type |
checkbox, radio |
- |
Inline label + control layout. No validation icon (the control shows its own state). |
data-no-icon |
boolean |
- |
Disable validation status icons |
data-floating-label |
boolean |
- |
Label starts inside the input and floats above on focus or value. A real placeholder keeps the label floated. See data-floating-label. |
data-valid |
boolean |
- |
Valid state (set by the component when a valid field has a value; can be set by hand) |
data-invalid |
boolean |
- |
Invalid state: reveals the error output and icon (set by the component; can be set by hand) |
data-pending |
boolean |
- |
Dims the field and blocks pointer input while something is in flight |
data-state |
validating |
- |
Async-check hook: warning border and a spinner in the icon slot |
data-message-invalid |
string |
Please check this field. |
Last-resort error message when neither a data-message-*, the authored error text nor the control supplies one (custom elements without a public validationMessage) |
data-label-* |
string |
- |
Localize generated text: show-password, hide-password, digit (Digit {n} of {total}), incomplete (Enter all {total} digits), plus the strength meter labels |
Input Attributes (for JS enhancements)
| Attribute |
Values |
Default |
Description |
data-type (on input) |
otp, pin |
- |
Enable OTP/PIN multi-box enhancement |
data-length (on input) |
4, 6, 8 |
6 |
Number of digits for OTP/PIN input |
data-strength, data-rules (on password input) |
boolean; length:N,uppercase,lowercase,number,special |
length:8 |
Strength meter + rules checklist. See data-strength. |
data-count (on textarea) |
"", words |
- |
Character/word counter, linked with aria-describedby. See data-count. |
data-message-* (on input) |
string |
- |
Custom error message per ValidityState key (see JS-Enhanced Validation) |
Element Structure
The form-field element groups a label, input control, and optional validation message.
| Child Element |
Purpose |
Key Attributes |
<label> |
Accessible field label |
for (matches input id) |
<input> / <textarea> / <select> |
Form control (or a form-associated custom element, see Custom controls) |
id, name, validation attrs, data-message-* |
<output class="hint"> |
Help text, collapses once the field is valid |
for |
<output class="error"> |
Error message, hidden until invalid. Authored text is the no-JS message and the JS fallback. |
for, aria-live="polite" |
ARIA wiring
When it upgrades, <form-field> wires the control for you:
aria-describedby lists the hint output(s) and the textarea counter, then the error output only while the field is invalid. Ids you already put in aria-describedby are kept (first); outputs without an id get one.
aria-invalid="true" mirrors the invalid state. For a radio group it goes on the field's radios; for OTP on the digit group; for custom elements on their inner combobox/group/input.
- The collapsed error output is
visibility: hidden, so it is not in the accessibility tree and a valid field never announces a stale error.
aria-errormessage is not used: screen-reader support is still too uneven.
Writing aria-describedby by hand is still fine (and is what the no-JS page uses).
1234567891011121314
<form-field> <label for="name">Full Name</label> <input type="text" id="name" name="name" required minlength="2" autocomplete="name" aria-describedby="name-hint name-error" /> <output id="name-hint" class="hint" for="name">As it appears on your ID.</output> <output id="name-error" class="error" for="name" aria-live="polite"> Please enter at least 2 characters. </output></form-field>
Input Types
Works with all standard form controls: text, email, password, textarea, and select.
123456789
<form-field> <label for="category">Category</label> <select id="category" name="category" required> <option value="" disabled selected>Select a category...</option> <option value="general">General Inquiry</option> <option value="support">Technical Support</option> <option value="sales">Sales Question</option> </select></form-field>
Password Toggle
Password inputs are automatically enhanced with a show/hide toggle button when JavaScript is available. No extra markup needed.
- Appears automatically when JavaScript loads
- Uses
aria-pressed and aria-label for accessibility; localize the label with data-label-show-password / data-label-hide-password on the <form-field>
- Positions adjust alongside validation icons
- Add
data-strength (and optionally data-rules) to the input for a strength meter and rules checklist
- Idempotent: moving or re-inserting the field never adds a second toggle or meter
1234567891011
<form-field> <label for="password">Password</label> <input type="password" id="password" name="password" required minlength="8" autocomplete="current-password" aria-describedby="password-msg" /> <output id="password-msg" class="error" for="password" aria-live="polite"> At least 8 characters required. </output></form-field>
Validation Status Icons
Form fields automatically display a checkmark (valid) or X (invalid) after user interaction. Icons are positioned inside the input's padding. Use data-no-icon to disable them.
1234567891011
<form-field> <label for="email">Email</label> <input type="email" id="email" name="email" required /></form-field> <form-field data-no-icon> <label for="search">Search</label> <input type="search" id="search" name="q" /></form-field>
OTP/PIN Input
Use data-type="otp" on the input for verification codes. Progressive enhancement: works as a standard text input without JS, enhances to multi-box with JS.
- Auto-focus moves to the next box after entering a digit
- Backspace moves focus to the previous box
- Arrow keys navigate between boxes
- Paste and one-time-code autofill fill multiple boxes at once
- The original input stays a real (visually hidden) text input: it submits the code and keeps
required and the length check (a pattern of \d{length} is added when you don't supply one), so an empty or partial code blocks submission. Its partial-code message defaults to "Enter all {total} digits" (data-message-patternmismatch or data-label-incomplete to change it)
- The boxes form a
role="group" named by the field's <label> and described by its hints; autocomplete="one-time-code" moves to the first box. Box names default to "Digit 1 of 6" (data-label-digit="Ziffer {n} von {total}" to localize)
123456789101112
<form-field data-no-icon> <label for="code">Verification code</label> <input type="text" id="code" name="code" data-type="otp" data-length="6" inputmode="numeric" pattern="[0-9]{6}" autocomplete="one-time-code" required aria-describedby="code-hint" /> <output id="code-hint" class="hint" for="code"> Enter the 6-digit code from your authenticator app. </output> <output class="error" for="code" aria-live="polite"></output></form-field>
Output Message Classes
Use class="hint" and class="error" on output elements for different message types.
| Class |
Visibility |
Use Case |
.hint |
Always visible (hides when valid) |
Format requirements, help text |
.error |
Only when invalid |
Error messages |
123456789101112
<form-field> <label for="username">Username</label> <input type="text" id="username" name="username" required minlength="3" maxlength="20" aria-describedby="username-hint username-error" /> <output id="username-hint" class="hint" for="username"> 3-20 characters, letters and numbers only. </output> <output id="username-error" class="error" for="username" aria-live="polite"> Please enter a valid username. </output></form-field>
Checkbox and Radio
Use data-type="checkbox" or data-type="radio" for inline label+input layout. Wrap radio groups in a <fieldset> with a <legend>.
1234567891011121314151617181920212223242526
<form-field data-type="checkbox"> <label> <input type="checkbox" id="terms" name="terms" required /> I agree to the Terms of Service </label></form-field> <fieldset> <legend>Preferred Contact Method</legend> <layout-stack data-layout-gap="xs"> <form-field data-type="radio"> <label> <input type="radio" name="contact" value="email" required /> Email </label> </form-field> <form-field data-type="radio"> <label> <input type="radio" name="contact" value="phone" /> Phone </label> </form-field> </layout-stack></fieldset>
CSS-Only Validation
Uses :user-valid and :user-invalid pseudo-classes to show validation states only after user interaction, preventing premature error states on page load.
123456789101112131415161718192021222324
form-field:has(:user-valid:required) { & :is(input, textarea, select) { border-color: var(--color-success); background-color: color-mix(in oklab, var(--color-success) 5%, transparent); } & output.hint { max-block-size: 0; opacity: 0; }} form-field:has(:user-invalid) { & :is(input, textarea, select) { border-color: var(--color-error); } & output.error { max-block-size: 4lh; opacity: 1; visibility: visible; }}
JS-Enhanced Validation
Add data-validate to a <form> to enable features CSS can't handle: custom error messages, cross-field validation, checkbox group constraints, and error summaries. Without it, everything works as pure CSS validation.
Form Attributes
| Attribute |
On |
Description |
data-validate |
<form> |
Opt-in. No value = field-level errors (+ summary if present). "summary" = summary only. |
data-submit |
<form> |
Submit mode: "native" (default), "event" (dispatches vb:submit), "fetch" (async with loading/success/error states). |
Custom Error Message Attributes
Attribute names map directly to ValidityState keys. Place these on the input element.
| Attribute |
ValidityState Key |
When Triggered |
data-message-valuemissing |
valueMissing |
required field is empty |
data-message-typemismatch |
typeMismatch |
type="email" / type="url" format wrong |
data-message-patternmismatch |
patternMismatch |
pattern regex fails |
data-message-tooshort |
tooShort |
Below minlength |
data-message-toolong |
tooLong |
Above maxlength |
data-message-rangeunderflow |
rangeUnderflow |
Below min |
data-message-rangeoverflow |
rangeOverflow |
Above max |
data-message-stepmismatch |
stepMismatch |
Not on step interval |
data-message-badinput |
badInput |
The browser can't parse the entry (e.g. letters in type="number") |
data-message-customerror |
customError |
setCustomValidity() was called; without this attribute the custom message itself is shown |
Message order: the matching data-message-* → (for custom errors and custom elements) the control's own validationMessage → the text authored inside output.error → the browser's validationMessage → data-message-invalid.
Cross-Field and Group Attributes
| Attribute |
On |
Description |
data-match |
input |
ID of field that must have the same value |
data-message-match |
input |
Custom message when data-match fails |
data-min-checked |
fieldset |
Minimum number of checked checkboxes |
data-max-checked |
fieldset |
Maximum number of checked checkboxes |
Web Component API
<form-field> upgrades to a web component when JS loads. It provides these methods for programmatic use:
| Method / Property |
Returns |
Description |
validate({ show = true } = {}) |
boolean |
Validate the field and show the result immediately (no blur needed) — error text, data-invalid, aria-invalid, describedby. The form coordinator calls it on submit. { show: false } only returns validity. |
setError(message) |
- |
Show a programmatic error (e.g. from server validation). Also sets it as the native control's custom validity so the form won't submit. Cleared on the user's next edit; a custom error set by other code (e.g. data-match) is never cleared by the field. |
clearError() |
- |
Clear the field's programmatic error and return to the neutral state. |
fieldName |
string |
Human-readable field name from the label or legend. |
input |
HTMLElement |
The bound control: the native input/textarea/select, or the form-associated custom element. |
form-field:upgraded (event) |
- |
Bubbles once the field has bound its control. |
Timing: the field validates when focus leaves it (moving between its own parts — password toggle, OTP boxes, a combobox popup — doesn't count), then re-validates on every edit once an error has been shown. It also validates when the browser fires invalid (native submit, checkValidity()). Its state survives being moved in the DOM.
1234567891011121314
<form data-validate> <form-field> <label for="email">Email</label> <input type="email" id="email" name="email" required minlength="5" data-message-valuemissing="Email is required" data-message-typemismatch="Please enter a valid email address" data-message-tooshort="Email seems too short" aria-describedby="email-error" /> <output id="email-error" class="error" for="email" aria-live="polite"></output> </form-field> <button type="submit">Submit</button></form>
123456789101112131415161718192021222324252627
<form data-validate> <form-field> <label for="password">Password</label> <input type="password" id="password" name="password" required minlength="8" data-message-valuemissing="Password is required" data-message-tooshort="At least 8 characters" autocomplete="new-password" aria-describedby="password-error" /> <output id="password-error" class="error" for="password" aria-live="polite"></output> </form-field> <form-field> <label for="confirm">Confirm Password</label> <input type="password" id="confirm" name="confirm" required data-match="password" data-message-valuemissing="Please confirm your password" data-message-match="Passwords do not match" autocomplete="new-password" aria-describedby="confirm-error" /> <output id="confirm-error" class="error" for="confirm" aria-live="polite"></output> </form-field> <button type="submit">Create Account</button></form>
123456789101112131415161718
<form data-validate> <fieldset data-min-checked="1" data-max-checked="3" data-message-min-checked="Select at least one" data-message-max-checked="Maximum 3 allowed"> <legend>Interests</legend> <form-field data-type="checkbox"> <label><input type="checkbox" name="interests" value="music" /> Music</label> </form-field> <form-field data-type="checkbox"> <label><input type="checkbox" name="interests" value="sport" /> Sport</label> </form-field> <form-field data-type="checkbox"> <label><input type="checkbox" name="interests" value="tech" /> Tech</label> </form-field> <output aria-live="polite"></output> </fieldset> <button type="submit">Save</button></form>
Custom Controls
A form-associated custom element inside the field — <date-picker>, <star-rating>, <combo-box> — becomes the bound control in preference to any native input inside it. The field reads its validity / validationMessage when exposed (date-picker), otherwise its :invalid state, and listens for its input, change, <tag>:change and invalid events. If the custom element is defined after the field upgrades, the field re-binds to it.
Put data-message-valuemissing on the custom element (or the field) for the required message; otherwise the authored error text is used.
12345
<form-field> <star-rating name="rating" label="Your rating" required data-message-valuemissing="Please choose a rating"></star-rating> <output class="error" aria-live="polite"></output></form-field>
setError() on a custom control is display-only (its validity lives in its own ElementInternals) and clears on the next change.
Error Summary
Add an <output class="error-summary"> inside your form for a consolidated list of all errors on submit.
| Mode |
Attribute |
Behavior |
| Field-level only |
data-validate (no summary output) |
Errors appear inline next to each field |
| Summary only |
data-validate="summary" |
Summary at top, field-level errors hidden |
| Both |
data-validate + summary output present |
Summary at top AND inline errors on each field |
12345678910111213141516171819202122232425
<form data-validate> <div data-form-summary role="alert" tabindex="-1" hidden> <h2>There are problems with your submission</h2> <ul data-summary-list></ul> </div> <form-field> <label for="name">Name</label> <input id="name" type="text" required data-message-valuemissing="Name is required" aria-describedby="name-error" /> <output id="name-error" class="error" for="name" aria-live="polite"></output> </form-field> <button type="submit">Submit</button></form> <form data-validate="summary"> <output class="error-summary" role="alert" aria-live="polite" tabindex="-1"></output> </form>
Complete Contact Form
123456789101112131415161718192021222324252627282930313233343536373839404142434445
<form action="/api/contact" method="POST"> <layout-stack data-layout-gap="m"> <form-field> <label for="name">Name</label> <input type="text" id="name" name="name" required minlength="2" autocomplete="name" aria-describedby="name-error" /> <output id="name-error" class="error" for="name" aria-live="polite"> Please enter your name (at least 2 characters) </output> </form-field> <form-field> <label for="email">Email</label> <input type="email" id="email" name="email" required autocomplete="email" aria-describedby="email-error" /> <output id="email-error" class="error" for="email" aria-live="polite"> Please enter a valid email address </output> </form-field> <form-field> <label for="subject">Subject</label> <select id="subject" name="subject" required> <option value="" disabled selected>Select a subject...</option> <option value="general">General Inquiry</option> <option value="support">Technical Support</option> <option value="feedback">Feedback</option> </select> </form-field> <form-field> <label for="message">Message</label> <textarea id="message" name="message" required minlength="10" rows="5" aria-describedby="message-error"></textarea> <output id="message-error" class="error" for="message" aria-live="polite"> Please enter your message (at least 10 characters) </output> </form-field> <button type="submit">Send Message</button> </layout-stack></form>
Why Use <output> for Messages?
- Purpose-built: Represents the result of a calculation or user action
- Native association: Has
for attribute to link to input(s)
- Accessible: Works naturally with
aria-live for screen readers
- No JavaScript required: Can show different states via CSS
Accessibility Checklist
- Every
<input> has a <label> with matching for/id
- Required fields use the
required attribute
- Validation messages use
<output> with aria-live="polite"
- Inputs link to messages via
aria-describedby (wired automatically on upgrade; author it too for the no-JS page)
- The required asterisk is decorative and silent; the control's native
required state is what screen readers announce
- In forced-colors mode the state icons switch to system colours and invalid controls get a double border
- Form controls have appropriate
autocomplete values
- Error states don't rely on color alone (include text)
Related
Enhancement attributes for the control inside