Course contentsShow
← Web Development
Lesson 925 of 2,98216. Forms and ValidationFree lesson

Error Message Association

Linking error messages to inputs with aria-describedby and ensuring errors are announced when fields are focused.

Error Message Association

What you'll learn: How to programmatically link error messages to form inputs so assistive technologies announce them correctly when users interact with invalid fields.

Why Association Matters

When a screen reader user focuses on an invalid input field, they need to immediately hear what's wrong. Without proper association, error messages might exist visually on the page but remain invisible to assistive technologies—like putting up a "Wrong Way" sign that's only visible to some drivers.

Using aria-describedby

The aria-describedby attribute creates a programmatic link between a form input and one or more elements that describe it (like error messages):

<label for="email">Email Address</label>
<input 
  type="email" 
  id="email" 
  aria-describedby="email-error"
  aria-invalid="true">
<span id="email-error" class="error-message">
  Please enter a valid email address
</span>

When a screen reader focuses this input, it automatically reads: "Email Address, invalid data, Please enter a valid email address."

Dynamic Association

Add the aria-describedby attribute only when an error exists:

const emailInput = document.getElementById('email');
const errorSpan = document.getElementById('email-error');

if (!emailInput.validity.valid) {
  emailInput.setAttribute('aria-describedby', 'email-error');
  emailInput.setAttribute('aria-invalid', 'true');
  errorSpan.textContent = emailInput.validationMessage;
} else {
  emailInput.removeAttribute('aria-describedby');
  emailInput.removeAttribute('aria-invalid');
  errorSpan.textContent = '';
}

This ensures the error message is announced when focusing the field, providing immediate context about what needs fixing.

Key Takeaway: Use aria-describedby to link error messages to their inputs, and set aria-invalid="true" so screen readers announce validation errors the moment users focus invalid fields, creating an accessible validation experience for all users.