HTML Form Error Summary Accessible

Show form validation errors in an accessible summary with aria-live and focus management.

HtmlForm Validation

Code

snippet
<form id="form" novalidate>
  <div role="alert" aria-live="assertive" id="errors" hidden></div>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required aria-describedby="email-error">
  <span id="email-error" class="error" hidden></span>
  <button type="submit">Submit</button>
</form>
<script>
  form.addEventListener('submit', (e) => {
    if (!form.checkValidity()) {
      e.preventDefault();
      const errors = [...form.elements].filter(el => !el.validity.valid);
      document.getElementById('errors').innerHTML = errors.map(el => '<li>' + el.name + ': invalid</li>').join('');
      document.getElementById('errors').hidden = false;
      errors[0].focus();
    }
  });
</script>