slop audit
Blog post 87 / Accessibility and visual design

Accessible form errors: markup, focus, and recovery tests

Build accessible form errors with aria-invalid, linked field descriptions, and a focused error summary. Test correction and resubmission before launch.

By Slop Audit · 8 min read

Accessible form errors identify the field that failed, explain how to correct it, and give the visitor a reliable way back to that field. A red border or a toast saying “Something went wrong” leaves too much work to the user. Build the error message, its programmatic association, and the keyboard recovery path together.

This guide implements custom client-side feedback for a small form. Use the website form testing checklist for the broader submission, network, and server-validation contract.

Choose native validation or custom accessible form errors

Start with native constraints such as required and type="email". Browsers can prevent invalid submissions and provide their own feedback. Custom validation takes over that presentation, so it must supply the messages and recovery behavior that users need. The MDN constraint validation guide explains how constraints, validity states, and novalidate interact.

Keep these requirements separate:

  • Identify the failing input and describe the problem in text. Color alone is insufficient. W3C Error Identification.
  • Suggest a correction when it is known and appropriate. “Enter an email address such as name@example.com” is more actionable than “Invalid value.” W3C Error Suggestion.
  • Preserve the visible label. Put supporting instructions and errors in the description rather than replacing the field's name. See the accessible name guide.

Decide when validation runs. The example below waits for submission and revalidates on the next submission. It does not mark untouched required fields invalid when the page opens. W3C's ARIA21 technique explains that aria-invalid="true" should follow validation, and that omitting it or using false represents the non-error state.

Connect the label, hint, and field error

The following HTML and JavaScript form a local demonstration. Put both blocks in a test page. It validates one required email field and keeps an optional name unchanged. The valid path deliberately stops before sending data; “ready to submit” is not a subscription confirmation.

<form id="signup" action="/subscribe" method="post">
  <div id="error-summary" role="region"
       aria-labelledby="error-title" tabindex="-1" hidden>
    <h2 id="error-title">There is a problem</h2>
    <ul>
      <li><a id="email-error-link" href="#email"></a></li>
    </ul>
  </div>

  <label for="name">Name (optional)</label>
  <input id="name" name="name" autocomplete="name">

  <label for="email">Email (required)</label>
  <p id="email-hint">We send release updates to this address.</p>
  <input id="email" name="email" type="email"
         autocomplete="email" required aria-describedby="email-hint">
  <p id="email-error" hidden></p>

  <button type="submit">Continue</button>
  <p id="signup-status" role="status"></p>
</form>

The error paragraph has its own stable ID. On failure, add that ID to aria-describedby alongside the hint ID. On successful revalidation, remove only the error association and preserve the hint. W3C's form notification tutorial describes associating field feedback with controls and providing links from an error list to the affected fields.

aria-invalid communicates the invalid state; it does not contain the explanation or run validation. An input can have the correct state attribute while its error text remains unconnected. Check both the state and the computed accessible description.

The initial HTML leaves native validation enabled. JavaScript will turn off the browser's interactive validation only after installing the custom handlers. Without JavaScript, the browser still applies the HTML constraints; the /subscribe endpoint would need to exist and validate the submitted data in a production application.

Show the summary and manage keyboard recovery

<script type="module">
  const form = document.querySelector("#signup");
  const email = document.querySelector("#email");
  const error = document.querySelector("#email-error");
  const summary = document.querySelector("#error-summary");
  const errorLink = document.querySelector("#email-error-link");
  const status = document.querySelector("#signup-status");

  errorLink.addEventListener("click", (event) => {
    event.preventDefault();
    email.focus();
  });

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    status.textContent = "";

    if (!email.validity.valid) {
      const message = email.validity.valueMissing
        ? "Enter your email address."
        : "Enter an email address such as name@example.com.";
      error.textContent = message;
      error.hidden = false;
      email.setAttribute("aria-invalid", "true");
      email.setAttribute("aria-describedby", "email-hint email-error");
      errorLink.textContent = message;
      summary.hidden = false;
      summary.focus();
      return;
    }

    email.removeAttribute("aria-invalid");
    email.setAttribute("aria-describedby", "email-hint");
    error.hidden = true;
    error.textContent = "";
    summary.hidden = true;
    status.textContent = "Email format accepted; ready to submit.";
    // Demo only: no request has been sent.
  });

  form.noValidate = true;
</script>

After an invalid submission, focus moves to the visible summary. Its link names the problem and explicitly focuses the email field when activated. tabindex="-1" permits programmatic focus without adding the summary to the normal Tab sequence. W3C's design-system form error guidance uses a focusable summary and links to the fields with errors.

This example uses focus to bring the failure to the visitor's attention. It does not also make every error an assertive alert. Test whether your chosen combination repeats messages unnecessarily. For background progress and completion feedback that leaves focus in place, use the aria-live implementation guide.

In a longer form, build one summary item per failing field and keep the inline and summary wording consistent. Do not focus the summary after every keystroke. Retain entered values and let users correct one field without resetting the others.

Style the error text and invalid control so the problem is visible without color alone. Keep an obvious outline on the focused summary, links, and inputs. Test wrapping at narrow widths and browser zoom; a long error must not be clipped by a fixed-height container.

Map server errors to the same recovery path

A syntactically valid address can still be rejected by the application. The production handler needs to send the request, validate on the server, and map known field errors into the same inline and summary UI. Do not announce success until the server confirms the intended outcome.

Keep server responses structured: use a field key such as email and an application error code, then select a safe message in the client. Insert messages as text rather than HTML. Preserve other field values when a response rejects one input.

Distinguish field errors from service failures. If the service is unavailable, a form-level message such as “We could not submit this form. Try again” is more accurate than marking the email invalid. Restore the submit action after failure and test retrying. The form QA checklist covers those request outcomes separately.

Test accessible form errors through correction

This Playwright test assumes a configured baseURL and a /signup-demo route containing the two blocks above. Install @playwright/test in the application being tested. It protects the initial state, both error messages, the summary link, preserved values, and cleanup after correction.

import { expect, test } from "@playwright/test";

for (const width of [375, 1280]) {
  test(`form error recovery at ${width}px`, async ({ page }) => {
    await page.setViewportSize({ width, height: 900 });
    await page.goto("/signup-demo");
    const email = page.getByRole("textbox", { name: "Email (required)" });
    const name = page.getByRole("textbox", { name: "Name (optional)" });
    const summary = page.getByRole("region", { name: "There is a problem" });
    const submit = page.getByRole("button", { name: "Continue" });
    const hint = "We send release updates to this address.";

    await expect(email).not.toHaveAttribute("aria-invalid", "true");
    await expect(email).toHaveAccessibleDescription(hint);
    await name.fill("Sam");
    await submit.focus();
    await submit.press("Enter");
    await expect(summary).toBeFocused();
    await expect(email).toHaveAttribute("aria-invalid", "true");
    await expect(email).toHaveAccessibleDescription(
      `${hint} Enter your email address.`
    );

    await page.keyboard.press("Tab");
    const errorLink = summary.getByRole("link");
    await expect(errorLink).toBeFocused();
    await errorLink.press("Enter");
    await expect(email).toBeFocused();
    await email.fill("not-an-email");
    await email.press("Enter");
    await expect(summary).toBeFocused();
    await expect(errorLink).toHaveText(
      "Enter an email address such as name@example.com."
    );

    await errorLink.press("Enter");
    await email.fill("sam@example.com");
    await email.press("Enter");
    await expect(summary).toBeHidden();
    await expect(email).not.toHaveAttribute("aria-invalid", "true");
    await expect(email).toHaveAccessibleDescription(hint);
    await expect(name).toHaveValue("Sam");
    await expect(page.getByRole("status")).toHaveText(
      "Email format accepted; ready to submit."
    );
  });
}

Playwright's assertion reference documents the retrying focus, attribute, and accessible-description assertions used here. Extend this test to the real server response, a failed request, and repeated correction before treating the production flow as verified.

Browser assertions cannot establish what a screen reader actually announces. Manually test the summary, field description, invalid state, and correction path with the browser and assistive technology combinations you support. Use the keyboard accessibility testing guide to check the surrounding navigation and focus order.

Check the deployed form with Slop Audit

After fixing the flow, run Slop Audit on the public form URL. Review its form-label evidence and any observed axe accessibility findings, repair the reported selectors, and rescan the same route. That provides a useful check of the deployed page alongside your form tests.

Slop Audit's bounded public-page audit does not prove that a form can be submitted successfully, that every error state was exercised, or that a screen reader announced the right message. Keep the recovery test and manual review as release evidence. Playwright's accessibility testing guide likewise explains why automated checks need manual assessment.