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.

TypescriptForm Validation

Code

typescriptsnippet
20 lines
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 — document will 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

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.