Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

Constraint Validation and Error Messages Everyone Can Perceive

Declare constraints on the fields themselves, take over the submit path, and report failures with inline messages, a focused error summary and the ARIA wiring that lets screen readers announce all of it.

Contentsand lesson path

What you will learn

  • Validate with native constraints and a shared schema, showing inline errors linked to their fields and an error summary that screen readers announce.

Prerequisites: React Components & State

01. The problem

Out of the box, a browser validates a form when it is submitted: required fields must be filled, emails must look like emails, numbers must sit inside their range. If a field fails, submission stops and the browser shows a small speech bubble on the first invalid field. That default is honest work, but it has two weaknesses. The bubbles vanish as soon as the user moves on, so nobody can review all the problems at once. And the announcement reaches nobody reliably: screen readers do not consistently read the bubbles, magnifier users may not be looking at the field, and the styling is not yours to fix.

This walk-through builds the pattern that fixes both, using the booking form for a shared desk. First the constraints are declared on the fields themselves, so the browser keeps computing validity even when the bubbles are switched off. Then the submit path is taken over with JavaScript, and every failure is reported twice: as an inline message tied to its field, and as an error summary at the top that receives focus and links to each field. A screen reader user hears the summary when it takes focus, jumps to any field from it, and hears the message again when the field gets focus.

02. Step 1: declare the constraints on the fields

Constraints are attributes: required, type, min, max, minlength, pattern, step. They belong in the markup because they describe the data, not the interaction — the browser, assistive technology and any script can all read them. The form below also carries novalidate, which stops the browser from blocking submission and showing its bubbles. Validity is still computed — novalidate only switches off the blocking, which is exactly what lets this lesson's own messages replace the bubbles.

HTML · booking.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Book a desk - Workshop Notes</title>
    <style>
      body { font-family: system-ui, sans-serif; max-width: 32rem;
             margin: 2rem auto; }
      label { display: block; margin-top: 1rem; }
      .field-error { color: #a4262c; margin: 0.25rem 0 0; }
      [aria-invalid="true"] { border: 2px solid #a4262c; }
      .error-summary { border: 2px solid #a4262c; padding: 0.5rem 1rem; }
      .error-summary a { color: #a4262c; }
    </style>
  </head>
  <body>
    <h1>Book a desk</h1>
    <form id="booking" novalidate>
      <div id="summary" class="error-summary" tabindex="-1" hidden>
        <p>There is a problem:</p>
        <ul></ul>
      </div>

      <label for="name">Name</label>
      <input id="name" name="name" type="text" required
             aria-describedby="name-error">
      <p class="field-error" id="name-error" hidden></p>

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

      <label for="date">Date</label>
      <input id="date" name="date" type="date" required
             min="2026-11-02" aria-describedby="date-error">
      <p class="field-error" id="date-error" hidden></p>

      <label for="guests">Guests (1 to 6)</label>
      <input id="guests" name="guests" type="number" required
             min="1" max="6" aria-describedby="guests-error">
      <p class="field-error" id="guests-error" hidden></p>

      <button type="submit">Book the desk</button>
      <p id="confirmation" role="status" hidden>Desk booked.</p>
    </form>
    <script src="booking.js"></script>
  </body>
</html>

Note the two pieces of ARIA wiring that exist before any JavaScript runs. Each field points aria-describedby at its message element, so the message becomes part of the field's description: on focus, a screen reader announces name, role, value and then that description. Each message <p> starts hidden and empty — a hidden element is ignored by assistive technology, so an empty description is harmless. The summary box has tabindex="-1" so it can take focus programmatically even though it is not part of the tab order.

03. Step 2: read validity from the fields

Every constrained element exposes the state the browser computes. el.checkValidity() returns whether the element is valid; el.validity says why not, through flags such as valueMissing, typeMismatch, rangeUnderflow and customError; and el.validationMessage holds the browser's own message for the failed constraint. The custom rule — this venue is closed at weekends — is layered on with setCustomValidity(): a non-empty string marks the field invalid with customError set and becomes its validationMessage, and setCustomValidity('') clears it again. Your script never has to re-derive any of this; it only translates flags into human sentences.

JavaScript · booking.js, part 1
const form = document.querySelector('#booking');
const summary = document.querySelector('#summary');
const summaryList = summary.querySelector('ul');
const confirmation = document.querySelector('#confirmation');
const fields = ['name', 'email', 'date', 'guests'].map((n) => form.elements[n]);

// One custom rule, kept next to the native constraints.
function applyCustomRules() {
  const date = form.elements.date;
  const day = new Date(`${date.value}T00:00:00`).getDay();
  const closed = date.value !== '' && (day === 0 || day === 6);
  date.setCustomValidity(closed ? 'We are closed at weekends.' : '');
}

function messageFor(field) {
  const v = field.validity;
  if (v.valueMissing) return 'This field is required.';
  if (v.typeMismatch) return 'Enter a valid email address.';
  if (v.rangeUnderflow && field.type === 'date') {
    return `Choose ${field.min} or later.`;
  }
  if (v.rangeUnderflow || v.rangeOverflow) return 'Choose 1 to 6 guests.';
  if (v.customError) return field.validationMessage;
  return '';
}

Two details inside messageFor matter. First, the range flags are shared by two fields, so the date gets its own sentence built from its min attribute; a single "Choose 1 to 6 guests." would appear next to the date field too. Second, the order: customError is checked last because setCustomValidity and the native flags are independent. Sunday 1 November is both before the minimum date and a weekend, so it sets rangeUnderflow and customError together. "Choose 2026-11-02 or later." is the more useful sentence there, because picking a weekday such as Friday 30 October would fix the weekend rule and still fail the minimum. Checking customError first would hide the constraint the user has to satisfy anyway.

04. Step 3: report inline, then summarise and focus

Showing an error means three moves on the field: put the sentence into its message element, unhide that element, and set aria-invalid="true" so the state is exposed. Clearing is the reverse. The summary lists every failure as a link to its field, and then takes focus. Focus is the announcement: a screen reader reads the focused element, so the user hears "There is a problem" and the linked list right away, and can jump to any field from the links. Colour and position do the rest for sighted users, and the information is never carried by colour alone.

JavaScript · booking.js, part 2
function showFieldError(field, message) {
  const output = document.querySelector(`#${field.id}-error`);
  output.textContent = message;
  output.hidden = message === '';
  if (message === '') {
    field.removeAttribute('aria-invalid');
  } else {
    field.setAttribute('aria-invalid', 'true');
  }
}

function validate() {
  applyCustomRules();
  const failed = [];
  for (const field of fields) {
    const message = messageFor(field);
    showFieldError(field, message);
    if (message !== '') failed.push({ field, message });
  }
  summaryList.innerHTML = '';
  if (failed.length === 0) {
    summary.hidden = true;
    return true;
  }
  for (const { field, message } of failed) {
    const link = document.createElement('a');
    link.href = `#${field.id}`;
    link.textContent = message;
    const item = document.createElement('li');
    item.append(link);
    summaryList.append(item);
  }
  summary.hidden = false;
  summary.focus(); // moves attention; screen readers read the links
  return false;
}

form.addEventListener('submit', (event) => {
  event.preventDefault(); // novalidate: we own the submit path
  confirmation.hidden = true;
  if (validate()) {
    confirmation.hidden = false;
  }
});

// Once the form has been submitted, clear each error as it is fixed.
form.addEventListener('input', (event) => {
  if (summary.hidden) return;
  applyCustomRules();
  if (event.target.checkValidity()) showFieldError(event.target, '');
});

05. Step 4: run it and read the evidence

The script below drives the page with Playwright and prints what a user would experience: the browser's stored messages, where focus lands, and the ARIA attributes as the DOM holds them. Run it from the folder that holds booking.html, after a one-time setup there: npm init -y, npm install -D @playwright/[email protected] and npx playwright install chromium.

JavaScript · validation-check.mjs (Playwright 1.64, Chromium 156)
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
const { chromium } = createRequire(process.cwd() + '/package.json')
  ('@playwright/test');
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(pathToFileURL('booking.html').href);

console.log('1. empty email: checkValidity =',
  await page.$eval('#email', (el) => el.checkValidity()),
  '| message =',
  await page.$eval('#email', (el) => JSON.stringify(el.validationMessage)));
await page.click('button[type=submit]');
console.log('2. focus after submit ->',
  await page.evaluate(() => document.activeElement.id));
const links = await page.$$eval('#summary a',
  (as) => as.map((a) => `${a.hash} ${a.textContent}`));
for (const l of links) console.log('   summary link:', l);
const described = await page.$eval('#email', (el) => ({
  invalid: el.getAttribute('aria-invalid'),
  target: document.getElementById(el.getAttribute('aria-describedby'))
    ?.textContent,
}));
console.log('3. email aria-invalid =', described.invalid,
  '| describedby reads =', JSON.stringify(described.target));
await page.fill('#email', '[email protected]');
await page.fill('#name', 'Rin');
await page.fill('#date', '2026-11-07'); // a Saturday
await page.fill('#guests', '2');
await page.click('button[type=submit]');
console.log('4. Saturday message ->',
  await page.$eval('#date-error', (el) => JSON.stringify(el.textContent)));
await page.fill('#date', '2026-11-01'); // a Sunday, before the minimum
await page.click('button[type=submit]');
console.log('5. too-early Sunday ->',
  await page.$eval('#date-error', (el) => JSON.stringify(el.textContent)));
await page.fill('#date', '2026-11-02'); // a Monday
await page.click('button[type=submit]');
console.log('6. after fixing: summary hidden =',
  await page.$eval('#summary', (el) => el.hidden),
  '| confirmation =',
  await page.$eval('#confirmation', (el) => JSON.stringify(el.textContent)));
await browser.close();
Expected output
1. empty email: checkValidity = false | message = "Please fill out this field."
2. focus after submit -> summary
   summary link: #name This field is required.
   summary link: #email This field is required.
   summary link: #date This field is required.
   summary link: #guests This field is required.
3. email aria-invalid = true | describedby reads = "This field is required."
4. Saturday message -> "We are closed at weekends."
5. too-early Sunday -> "Choose 2026-11-02 or later."
6. after fixing: summary hidden = true | confirmation = "Desk booked."

Each line is a promise kept. Line 1 shows the browser still knows the email is empty even with novalidate. Line 2 shows focus landing on the summary, which is what a screen reader user hears first. Line 3 shows the inline message is genuinely the field's description. Line 4 shows the custom rule speaking through the same channel as the native ones. Line 5 shows the date's own range message winning over the weekend rule for a date that breaks both. Line 6 shows the whole surface clearing itself once the data is right. Note the summary links point at the fields (#name, #email), so a keyboard user lands on the field with the message still announced by aria-describedby.

06. Check your understanding

Practice check · 3 questions

Constraints and reporting in practice

Three situations from the booking form.

Q1. A date field rejects weekends with setCustomValidity("We are closed at weekends."). The user then picks a Monday. What must the script do so the field becomes valid again?
Q2. What is the practical difference between field.checkValidity() and field.reportValidity()?
Q3. Why does booking.js revalidate a field on input only after the first failed submit?
Practice only: not graded, not saved, not evidence.

07. Apply it

Extend the booking form:

  1. Add a "Project code" text field with pattern="[A-Z]{3}-[0-9]{4}" and a message that shows the expected shape, such as "Use three capital letters, a dash, then four digits".
  2. Teach messageFor a sentence for patternMismatch and check that the summary lists it with the others.
  3. Pick a weekday and a Saturday, submit both, and watch the summary shrink to one link and then disappear.

Then read the WAI guidance on form notifications and check your page against it. If you use React, lesson 4 on form actions rebuilds this reporting inside an action.

08. Review prompt

Without looking back: which attributes declare constraints, and what does novalidate actually switch off? Name three flags on ValidityState and one sentence each. How does a field's error message become part of its announcement, and why does the summary take focus instead of appearing silently? What does setCustomValidity("") do, and when must you call it?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check