devcrea

Custom Inline Form Errors: novalidate, Constraint API & ARIA

Replace browser validation bubbles with accessible inline form errors using novalidate, the Constraint Validation API, aria-invalid, and aria-describedby.

// The short answer

Set form.noValidate = true in JavaScript to suppress native tooltips while keeping HTML5 validation as a no-JS fallback, then map el.validity flags to inline messages linked via aria-describedby and aria-invalid="true". Focus an error summary on submit, re-check invalid fields on input, clear cross-field setCustomValidity('') across all related inputs, and honor event.submitter?.formNoValidate for secondary submit buttons.

Full walkthrough, edge cases and why it works
In this guide · 7 sections
  1. 01Why Set noValidate in JavaScript Instead of HTML
  2. 02Mapping ValidityState Flags to Actionable Error Messages
  3. 03Complete 30-Line Inline Validation Pattern
  4. 04Wiring aria-invalid and aria-describedby Correctly
  5. 05Fixing the setCustomValidity() Stuck-Message Bug
  6. 06Bypassing Validation for Secondary Actions with formnovalidate
  7. 07Verification Checklist and Common Failure Modes

Swapping native browser validation bubbles for custom inline errors lets you keep the browser's built-in constraint engine while taking full control over layout, copy, focus, and accessibility. Set noValidate in JavaScript and read from the Constraint Validation API, and you can render inline field messages, an accessible error summary, and predictable focus behavior in roughly 30 lines of vanilla JavaScript.

  • Prerequisites: Standard HTML form controls with native validation attributes (required, type, minlength, pattern) and basic DOM event handling.
  • Core API surface: form.noValidate, form.checkValidity(), el.validity (ValidityState), el.setCustomValidity(), and event.submitter.formNoValidate.
  • Required ARIA wiring: aria-invalid="true" on failing controls, aria-describedby linking each control to its error container, and a focusable error summary (tabindex="-1").
  • Browser compatibility: Both the Constraint Validation API and event.submitter are Baseline Widely Available across all modern evergreen browsers.

Why Set noValidate in JavaScript Instead of HTML

Adding the novalidate attribute directly to <form novalidate> shuts off native browser validation right away. If your JavaScript bundle fails to load, throws an unhandled error, or gets blocked, the form submits with zero client-side checks.

Setting form.noValidate = true inside your script keeps progressive enhancement intact. Once your JavaScript runs, it suppresses the native tooltip bubbles and hands submit-time control to your handler. If JavaScript never runs, the browser falls back to its built-in validation automatically.

js2 lines
const form = document.querySelector('#signup-form');
form.noValidate = true;

Turning off native bubbles does not turn off the Constraint Validation API. Every control still checks its HTML attributes, updates its validity object, and responds to checkValidity() and reportValidity():

  • checkValidity() returns true or false and fires a cancelable invalid event on each failing control without showing any browser UI.
  • reportValidity() runs the same check, fires invalid events, focuses the first failing control, and displays the native browser bubble.

Mapping ValidityState Flags to Actionable Error Messages

Reading el.validationMessage gives you the browser's localized default string (such as "Please fill out this field"). Those strings change across browsers, ignore your field labels, and rarely satisfy WCAG 3.3.1 (Error Identification) and 3.3.3 (Error Suggestion) when read out of context.

Skip validationMessage and map the boolean flags on el.validity to specific, verb-led instructions that name the field and tell the user how to fix it.

js9 lines
function getErrorMessage(field) {
  const { validity } = field;
  if (validity.customError) return field.validationMessage;
  if (validity.valueMissing) return `Enter your ${field.dataset.label || field.name}.`;
  if (validity.typeMismatch) return 'Enter a valid email address (for example, name@example.com).';
  if (validity.tooShort) return `Use at least ${field.minLength} characters.`;
  if (validity.patternMismatch) return field.dataset.patternHint || 'Match the requested format.';
  return 'Check this field and try again.';
}

Checking validity.customError first means any message you set via setCustomValidity() takes priority over generic attribute flags.

If you would rather listen to the invalid event directly on the <form> element instead of looping over form.elements, pass { capture: true } to addEventListener. The invalid event never bubbles up the DOM tree, so a standard bubbling listener on <form> will not fire.

Complete 30-Line Inline Validation Pattern

A solid inline validation flow follows the "reward early, punish late" approach: validate the entire form on submit, move focus to the error summary or first invalid field, and then re-validate only invalid fields on input so each error clears the moment the user fixes it.

Begin with semantic HTML where every input gets a <label>, a dedicated error element with a matching id, and a hidden summary region at the top of the form:

html23 lines
<form id="signup-form" action="/signup" method="post">
  <div id="error-summary" role="alert" tabindex="-1" hidden>
    <p>Fix the following before submitting:</p>
    <ul></ul>
  </div>

  <div>
    <label for="email">Work email</label>
    <input id="email" name="email" type="email" required
           data-label="work email" aria-describedby="email-error">
    <p id="email-error" class="field-error" hidden></p>
  </div>

  <div>
    <label for="username">Username</label>
    <input id="username" name="username" type="text" required minlength="3"
           data-label="username" aria-describedby="username-error">
    <p id="username-error" class="field-error" hidden></p>
  </div>

  <button type="submit">Create account</button>
  <button type="submit" formnovalidate>Save draft</button>
</form>

Wire up the form with roughly 30 lines of JavaScript:

js36 lines
const form = document.querySelector('#signup-form');
const summary = document.querySelector('#error-summary');
const summaryList = summary.querySelector('ul');
form.noValidate = true;

function syncField(field) {
  const out = document.getElementById(`${field.id}-error`);
  const valid = field.validity.valid;
  if (valid) {
    field.removeAttribute('aria-invalid');
    if (out) { out.textContent = ''; out.hidden = true; }
    return null;
  }
  const msg = getErrorMessage(field);
  field.setAttribute('aria-invalid', 'true');
  if (out) { out.textContent = msg; out.hidden = false; }
  return { field, msg };
}

form.addEventListener('submit', (e) => {
  if (e.submitter?.formNoValidate) return;
  const errors = [...form.elements].filter((el) => el.willValidate).map(syncField).filter(Boolean);
  summaryList.innerHTML = '';
  summary.hidden = errors.length === 0;
  if (!errors.length) return;

  e.preventDefault();
  errors.forEach(({ field, msg }) => {
    summaryList.insertAdjacentHTML('beforeend', `<li><a href="#${field.id}">${msg}</a></li>`);
  });
  summary.focus();
});

form.addEventListener('input', (e) => {
  if (e.target.getAttribute('aria-invalid') === 'true') syncField(e.target);
});

Use the exact same error text in both the inline <p> and the summary <li> link. When your backend sends back client-side validation security field-level validation failures after a fetch() request, pass those messages into the same out container and set aria-invalid="true" so client and server errors share one consistent DOM structure.

Wiring aria-invalid and aria-describedby Correctly

Visual styling on its own fails WCAG 3.3.1. Even if you style failing inputs with CSS :user-invalid, browsers never sync :user-invalid with the accessibility tree automatically, you have to manage aria-invalid explicitly in JavaScript.

aria-invalid="true" vs. aria-invalid="false" vs. Removing the Attribute

aria-invalid is an enumerated ARIA attribute, not a boolean HTML attribute. Calling field.toggleAttribute('aria-invalid', !valid) is a classic mistake because toggleAttribute inserts aria-invalid="" (an empty string), which assistive technologies interpret as "false" or ignore altogether.

Call field.setAttribute('aria-invalid', 'true') whenever a field fails, and run field.removeAttribute('aria-invalid') once it passes. Removing the attribute puts the control back into its default valid state without cluttering your DOM with unnecessary aria-invalid="false" attributes on untouched fields.

aria-describedby vs. aria-errormessage and Live Regions

Connecting an input to its error message takes programmatic association so screen readers announce the error the moment you focus the field:

Mechanism Behavior & Spec Intent Practical Trade-off
aria-describedby Appends the referenced element's text to the control's accessible description. Broad, consistent support across browsers and screen readers. Safe default for production forms.
aria-errormessage Explicitly identifies an error message element when aria-invalid="true" is also set. Built specifically for validation errors, though support across browser and screen reader combinations has historically lagged behind aria-describedby.
aria-live="polite" on every field error Announces text changes dynamically as they happen in the DOM. Can trigger double announcements when paired with focus movement or an error summary role="alert".

If your input already relies on aria-describedby for a hint (such as aria-describedby="username-hint"), include both IDs separated by a space (aria-describedby="username-error username-hint"). Put the error ID first so assistive technology reads the error before the static hint.

Fixing the setCustomValidity() Stuck-Message Bug

Cross-field rules, like confirming a HTML password field validation input or making sure an end date comes after a start date, cannot be expressed with HTML attributes alone. You handle them with field.setCustomValidity(message).

  • Here is the catch: setCustomValidity() sets validity.customError = true and locks the field in an invalid state until you explicitly call setCustomValidity('') with an empty string. If you validate only on change or submit without clearing the custom message on input, the field stays stuck in an invalid state even after the user fixes the value.

Watch how the stuck-message bug happens in practice:

js7 lines
// BUG: Running setCustomValidity only on submit or change without clearing on input
confirmInput.addEventListener('change', () => {
  if (confirmInput.value !== passwordInput.value) {
    confirmInput.setCustomValidity('Enter the same password in both fields.');
  }
  // Missing else branch or missing listener on passwordInput leaves customError stuck
});

If the user edits passwordInput to match confirmInput, confirmInput's change event never fires. Its customError flag stays true, and the form refuses to submit.

Solve this by clearing and re-evaluating custom validity on input for every field involved in the rule:

js10 lines
function validatePasswordMatch() {
  const mismatch = confirmInput.value && confirmInput.value !== passwordInput.value;
  confirmInput.setCustomValidity(mismatch ? 'Enter the same password in both fields.' : '');
  if (confirmInput.getAttribute('aria-invalid') === 'true') {
    syncField(confirmInput);
  }
}

passwordInput.addEventListener('input', validatePasswordMatch);
confirmInput.addEventListener('input', validatePasswordMatch);

Because input fires before change and updates synchronously on every keystroke, calling setCustomValidity('') inside the input handler ensures validity.customError clears before the user clicks Submit.

Bypassing Validation for Secondary Actions with formnovalidate

Forms often need a secondary submit button, like Save draft, that sends partial data without triggering validation. In HTML, you add the formnovalidate attribute right to that button:

html1 line
<button type="submit" formnovalidate>Save draft</button>

Once you set form.noValidate = true in JavaScript, your custom submit listener runs for every submit button, including the draft button. If you fail to check which button triggered the submission, your script will block the draft save and show errors anyway.

Inspect event.submitter?.formNoValidate right at the top of your submit handler:

js4 lines
form.addEventListener('submit', (e) => {
  if (e.submitter?.formNoValidate) return;
  // Run custom validation for primary submit buttons
});

event.submitter points to the exact <button> or <input type="submit"> that kicked off the submit event, and formNoValidate reflects its formnovalidate attribute as a boolean.

Verification Checklist and Common Failure Modes

Before shipping custom inline validation, run your form through these four checks:

  1. Accessibility Tree check: Submit an empty form, open Chrome DevTools, select a failing <input>, and inspect the Accessibility pane. Verify that Invalid user entry (aria-invalid="true") is active and that Description holds the exact inline error text. Fix the field and confirm both clear.
  2. Keyboard-only navigation: Tab to the submit button and press Enter on an invalid form. Check that focus lands on #error-summary (or the first invalid field) and that clicking a summary link moves focus directly to the matching input.
  3. Stuck custom validity test: Trigger a setCustomValidity() error (like a mismatched confirmation field), fix the first field so both match, and submit right away without touching the second field. Confirm the form submits cleanly without blocking.
  4. JavaScript-disabled fallback: Turn off JavaScript in DevTools, reload the page, and submit the empty form. Verify that the browser's native validation bubbles appear because you applied noValidate in JavaScript instead of hardcoding it in HTML.

Common failure modes to watch for:

  • Missing tabindex="-1" on #error-summary: Calling summary.focus() on a <div> without tabindex="-1" fails silently, leaving keyboard focus stranded on the submit button.
  • Non-validating elements in form.elements: Looping over form.elements pulls in <button> and <fieldset> nodes, so filter with el.willValidate to check only submittable controls.
  • Double announcements: Putting aria-live="assertive" on individual field errors while also focusing a role="alert" error summary makes screen readers interrupt themselves or read the same error twice. Keep role="alert" on the summary and let aria-describedby handle per-field errors on focus.

Quick answers

Frequently asked questions

Why should you set novalidate in JavaScript instead of directly in the HTML form tag?

Setting form.noValidate = true in JavaScript keeps native browser validation working if your script fails to load, throws an error, or gets blocked. Hardcode the novalidate attribute in HTML, and the browser submits the form with zero client-side checks whenever JavaScript fails to run. Applying it inside your script gives you a reliable fallback while letting your custom handler take over once JavaScript runs.

Does adding novalidate disable the Constraint Validation API?

No, novalidate only stops the browser from blocking form submission and displaying its built-in tooltip bubbles. Every form control still checks its HTML validation attributes, updates its validity object, and responds to checkValidity(), reportValidity(), and setCustomValidity(). You keep the browser's constraint engine intact while rendering your own inline error markup.

Should you use aria-invalid='false' or remove the attribute when a field becomes valid?

Strip the aria-invalid attribute completely with removeAttribute('aria-invalid') as soon as a field passes validation. Call setAttribute('aria-invalid', 'true') when validation fails, and skip toggleAttribute('aria-invalid') because it inserts an empty string that assistive technologies do not read as true. Leaving untouched and valid fields free of aria-invalid='false' prevents redundant screen reader announcements.

Should you use aria-describedby or aria-errormessage for inline form errors?

Default to aria-describedby because modern browsers and screen readers support it reliably. Although aria-errormessage was built specifically for validation messages paired with aria-invalid='true', support across assistive technology combinations still lags behind aria-describedby. When an input already links to a hint via aria-describedby, put the error element's ID first and follow it with a space and the hint ID.

Why does setCustomValidity() keep blocking form submission after the user fixes the input?

Passing a non-empty message to setCustomValidity() flips validity.customError to true and locks the field in an invalid state until you explicitly pass an empty string (''). If you only clear it inside a change or submit listener, editing a related field or typing new characters leaves that old customError flag active. Attach an input event listener to every field involved in the rule and call setCustomValidity('') as soon as the condition passes.

How do you prevent a Save draft button from triggering custom form validation?

Add the formnovalidate attribute to the secondary submit button in HTML and check event.submitter?.formNoValidate at the top of your submit listener. Because form.noValidate = true routes every submission through your JavaScript handler, your script will otherwise block the draft button and display errors. Returning early when event.submitter?.formNoValidate is true lets the draft submit cleanly.

Why does an invalid event listener on a form element fail to fire?

The invalid event never bubbles up the DOM tree from individual inputs to the parent form element. A standard form.addEventListener('invalid', ...) listener only watches the bubble phase and will miss every field failure. Pass { capture: true } as the third argument to addEventListener if you want to catch invalid events at the form level.

Something wrong or out of date?

Tools change fast. Tell the editor what no longer works.