Intermediate level · Module 4: Browser Storage and Robust Forms · Lesson 2 of 3
Accessible Form Validation
Validate forms with HTML attributes and the Constraint Validation API, add custom rules and present errors accessibly.
In this lesson you will
- Use HTML validation attributes and the Constraint Validation API
- Show accessible, field-specific error messages
Key concepts
required, min, patterncheckValidity and setCustomValidityaria-describedbyfocus management
The lesson
HTML attributes give basic validation for free: required, type="email", min, max and pattern. In JavaScript, input.validity describes what is wrong and form.checkValidity() tests the whole form.
Custom rules, such as 'end date after start date' or 'amount within the remaining budget', can be added with setCustomValidity(message) or your own checks. Always validate again on the server; browser validation helps users but does not protect a server.
Make errors accessible: show the message next to the field, link it with aria-describedby, mark the field with aria-invalid="true" and move focus to the first invalid field so screen-reader and keyboard users find it.
Step by step
- Add required and min attributes to the budget form.
- Check validity in the submit handler.
- Add a custom rule for the remaining budget.
- Link error messages with aria-describedby and focus the first error.
Practice activity
Complete the budget form validation from the practical activity.
Expected result: Invalid submissions show clear messages beside the fields, focus moves to the first problem and valid data is saved.
Check your understanding
-
Is browser validation enough to protect a server?
Show answer
No; the server must validate again.
-
How is an error message linked to its field for screen readers?
Show answer
With aria-describedby pointing to the message's ID.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.