invalid Event Displays Per-Field Errors
The invalid event fires per failing control and does not bubble, so a form-level listener uses capture to route validationMessage into field slots.
Code
const form = document.querySelector('form') as HTMLFormElement;
const emailError = form.querySelector('#email-error') as HTMLElement;
// invalid fires per control that fails validation; it does not bubble out
// of the control, so a form-level listener needs the capture phase.
form.addEventListener(
'invalid',
(event) => {
const field = event.target as HTMLInputElement;
const slot = document.querySelector<HTMLElement>(`#${field.id}-error`);
if (slot) {
slot.textContent = field.validationMessage;
slot.hidden = false;
}
event.preventDefault(); // suppress the browser's built-in error bubble
},
true,
);
console.log('email-error slot ready:', emailError !== null);Under the hood — invalid Event Displays Per-Field Errors
Top-level bindings form, emailError hold the demo state — nothing sits inside a function scope.
What to watch for
- Behavior originates entirely in the standard library; external calls don’t exist here.
- This is browser-side code —
documentwill not resolve in Node.
Using it
The run emits 1 labeled section — email-error slot ready: — one per step.
Key statements
(event) => {
const field = event.target as HTMLInputElement;
const slot = document.querySelector<HTMLElement>(`#${field.id}-error`);
if (slot) {
slot.textContent = field.validationMessage;
slot.hidden = false;
}
event.preventDefault(); // suppress the browser's built-in error bubble
},
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does invalid Event Displays Per-Field Errors run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.