HTML Form Error Summary Accessible
Show form validation errors in an accessible summary with aria-live and focus management.
Code
<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>Report a problem with this exampleOpens a pre-filled issue on GitHub.