JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 13: Forms and ValidationLesson 65 of 150About 45 minutes

Lesson 65: Accessible form feedback

01Opening question

A red border says "something is wrong" to some people. What about people who cannot see colour, or who use a screen reader?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

The message is real text, linked to the field with aria-describedby, and the field is marked aria-invalid. Screen readers read the message when the field is focused.

const email = document.querySelector("#email");
const error = document.querySelector("#email-error");
email.setAttribute("aria-invalid", "true");
error.textContent = "Enter an email like name@example.com";
console.log(email.getAttribute("aria-describedby"), error.textContent);

03Objective and prerequisites

Learning objective: Show validation feedback that everyone can perceive: visible text messages linked with aria-describedby, aria-invalid, focus management and live regions.

You need: Lesson 64: Custom validation rules

Skills practised: Forms, Accessible feedback.

04Explanation

Every field needs a visible label (<label for="id">). Placeholders disappear when you type and are not labels.

Error messages must be text, not only colour. Put the message in an element near the field.

Link the message to the field with aria-describedby="message-id" and set aria-invalid="true" on the field, so screen readers announce both.

After a failed submit, move focus to the first invalid field (field.focus()) so keyboard and screen reader users land where the problem is.

05Definitions

aria-describedby
An attribute that links an element to the ids of elements that describe it, such as an error message.
aria-invalid
An attribute telling assistive technology that a field's value is invalid.
Live region
An area marked with aria-live or role="status" whose text changes are announced by screen readers.
Focus management
Moving keyboard focus deliberately, for example to the first invalid field.
Error summary
A list of all errors at the top of a form, usually with links to each field.

Open the full glossary

06Visual learning object

Accessible interaction laboratory. Submit a form with errors and see which attributes, messages, live announcements and focus changes a screen reader user would get.

Loading the interactive object…

Open the full Accessible interaction laboratory page with its guided experiment.

07Examples

ex-065-01A linked error message Browser page (sandboxed preview)

One function sets the text, aria-invalid and the link together.

function showError(field, message) {
  const box = document.getElementById(field.getAttribute("aria-describedby"));
  box.textContent = message;
  if (message) field.setAttribute("aria-invalid", "true");
  else field.removeAttribute("aria-invalid");
}
const name = document.querySelector("#name");
showError(name, "Enter your name");
console.log(name.getAttribute("aria-invalid"), document.querySelector("#name-error").textContent);
showError(name, "");
console.log(name.getAttribute("aria-invalid"), JSON.stringify(document.querySelector("#name-error").textContent));
Sample input
None
Expected output
true Enter your name null ""
Common mistake
Showing a red border without any text.
Try this
Add a class to the field for styling as well.
Source
examples/ex-065-01-show-error.js

ex-065-02Focus the first problem Browser page (sandboxed preview)

After a failed submit, focus moves to the first invalid field.

const form = document.querySelector("#f");
form.addEventListener("submit", (event) => {
  event.preventDefault();
  const invalid = [...form.elements].filter((el) => el.name && !el.checkValidity());
  if (invalid.length) invalid[0].focus();
  console.log(invalid.length + " problem(s); focus on", document.activeElement.name);
});
form.elements.email.value = "kim@example.com";
form.requestSubmit();
Sample input
None
Expected output
1 problem(s); focus on phone
Common mistake
Leaving focus on the submit button so keyboard users must hunt for the error.
Try this
Also focus the field when its error message is clicked.
Source
examples/ex-065-02-focus-first.js

ex-065-03Announcing results Browser page (sandboxed preview)

A status region that already exists announces new text politely.

const form = document.querySelector("#f");
const status = document.querySelector("#status");
form.addEventListener("submit", (event) => {
  event.preventDefault();
  status.textContent = "Saved \u201c" + form.elements.q.value + "\u201d";
});
form.requestSubmit();
console.log(status.getAttribute("role"), status.textContent);
Sample input
None
Expected output
status Saved “lamp”
Common mistake
Creating the live region at the same moment as its message, so it is not announced.
Try this
Clear the status message after 3 seconds.
Source
examples/ex-065-03-live-status.js

ex-065-04An error summary Browser page (sandboxed preview)

A summary lists every error and links to each field.

const summary = document.querySelector("#summary");
function renderSummary(errors) {
  const list = summary.querySelector("ul");
  list.replaceChildren(...errors.map(({ id, message }) => {
    const li = document.createElement("li");
    const a = document.createElement("a");
    a.href = "#" + id;
    a.textContent = message;
    li.append(a);
    return li;
  }));
  summary.hidden = errors.length === 0;
  if (errors.length) summary.focus();
}
renderSummary([{ id: "u", message: "Enter a username" }, { id: "e", message: "Enter a valid email" }]);
console.log(summary.hidden, document.activeElement.id);
console.log([...summary.querySelectorAll("a")].map((a) => a.getAttribute("href")).join(" "));
Sample input
None
Expected output
false summary #u #e
Common mistake
Listing errors without links, so people must find each field themselves.
Try this
Build the errors list from the form's validity instead of by hand.
Source
examples/ex-065-04-summary.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

A field without a label

Connect a label to its field.

const field = document.querySelector("#postcode");
console.log(field.labels.length);

Accessible error helper

Keep text, aria-invalid and aria-describedby in sync.

function setError(field, message) {
  // TODO: put message in the element with id field.id + "-error",
  // set aria-describedby to that id, and set aria-invalid="true"
  // when there is a message or remove aria-invalid when there is not
}
const city = document.querySelector("#city");
setError(city, "Enter a city");
console.log(city.getAttribute("aria-invalid"), city.getAttribute("aria-describedby"), document.querySelector("#city-error").textContent);

Accessible form submission

Combine validation, messages, focus and a live status.

// On submit (preventDefault): for each named field, set its "<id>-error"
// text ("Required" for valueMissing, "Invalid" for any other problem, ""
// if valid) and aria-invalid; focus the first invalid field; set #status
// to "N error(s)" or "Thanks!".
// Then fill only the name with "Ana" and submit.

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <label for="q">Search</label><input id="q" aria-describedby="hint"><p id="hint">Try a city</p>
const q = document.getElementById("q");
console.log(q.labels[0].textContent, document.getElementById(q.getAttribute("aria-describedby")).textContent);

What is printed?

10Debugging investigation

The error is invisible to screen readers

Sighted users see "Use digits only", but screen reader users hear nothing about the error when they return to the field.

const phone = document.getElementById("phone");
function report(field, message) {
  document.getElementById(field.id + "-msg").textContent = message;
  field.style.borderColor = message ? "red" : "";
}
report(phone, "Use digits only");
console.log(phone.getAttribute("aria-describedby"), phone.getAttribute("aria-invalid"), document.getElementById("phone-msg").textContent);

More cases in the Debugging Detective Laboratory

11Practical scenario

Public service forms

Government services are required to meet accessibility standards. Their forms show an error summary with links, inline messages connected by aria-describedby, and move focus to the summary after submission, so every visitor can complete them with a keyboard or screen reader.

const checks = ["labels", "text errors", "aria-describedby", "aria-invalid", "focus", "live status"];
console.log(checks.length + " checks:", checks.join(", "));

12Knowledge check

1. Why is a red border alone not enough to show an error?

  • Borders are slow
  • Some people cannot perceive colour and screen readers do not announce it
  • Red is not allowed
  • Browsers remove borders

2. What does aria-describedby do?

  • Hides an element
  • Links a field to the element(s) that describe it
  • Validates a field
  • Sets a placeholder

3. Where should focus go after a failed submit?

  • Stay on the button
  • The first invalid field or an error summary
  • The page title
  • The browser address bar

4. Why is the Saved message not announced by screen readers?

const p = document.createElement("p");
p.setAttribute("role", "status");
p.textContent = "Saved";
document.body.append(p);
  • The live region is created at the same moment as its text
  • textContent is wrong
  • status must be a div
  • Messages cannot be announced

5. Is a placeholder a substitute for a label?

  • Yes
  • No, it disappears when typing and is not reliably announced
  • Only for emails
  • Only on mobile

6. Which is better for announcing an urgent payment failure?

  • role="alert"
  • A console.log
  • A colour change
  • A title change

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • A field without a label: Prints 1; The label is connected
  • Accessible error helper: Shows the error; Clears the error
  • Accessible form submission: Reports one error and focuses email; Email error says Required; Valid form says Thanks!

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-13-forms-and-validation/lesson-065-accessible-form-feedback/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Errors must be text, not only colour.
  • Link messages with aria-describedby and mark fields with aria-invalid.
  • Move focus to the first problem or an error summary.
  • Use live regions that already exist for dynamic messages.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation accessible form feedback
Context: I am learning accessible form feedback in JavaScript.
Task: Explain labels, aria-describedby, aria-invalid, focus management and live regions for form errors.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction accessible form feedback drill
Context: I have practised accessible form feedback.
Task: Give me six small form snippets and ask what a screen reader user would hear or where focus ends up.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging accessible form feedback bug
Context: Screen reader users say they cannot tell which field is wrong.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation accessible form feedback practice
Context: I finished the accessible form feedback exercises.
Task: Create three exercises that add accessible feedback to a form.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review accessible form feedback review
Context: Here is my code that uses accessible form feedback.
Task: Review my form for missing labels, colour-only errors and lost focus.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.