Constraint Validation API
The browser can check form controls against HTML constraints such as required, type, min, and pattern.
What you will learn
- How HTML constraints provide the first validation layer
- How to inspect validity and show a useful message
- Why validation in the browser does not replace server-side checks
Start with HTML
<label for="email">Email</label>
<input id="email" name="email" type="email" required>Use the most specific native input type and constraint that matches the data. The browser can prevent submission and provide built-in feedback.
Inspect validity
const form = document.querySelector('form');
const email = document.querySelector('#email');
form.addEventListener('submit', (event) => {
if (!email.validity.valid) {
event.preventDefault();
email.focus();
}
});Properties such as validity.valueMissing and validity.typeMismatch explain why a control is invalid. Keep the message near the control and make it understandable without color alone.
Common mistakes
- Do not rely only on JavaScript; keep constraints in HTML when possible.
- Always validate and authorize submitted data on the server.
- Do not erase the browser's focus indicator while showing an error.
- Tell the user how to fix the value, not only that it is invalid.