Validation APIs
The Constraint Validation API is a set of browser features that check form fields against rules you declare in HTML, such as required, type="email", minlength or pattern. JavaScript can read the result of these checks, trigger them on demand, show custom messages and add rules HTML cannot express. Using the built-in API gives you consistent validation and accessible error messages with very little code.
Rules declared in HTML
requiredrejects an empty field.type="email",type="url"andtype="number"check the format.minlengthandmaxlengthlimit text length.min,maxandsteprestrict numbers and dates.patterntakes a regular expression the whole value must match.
The browser checks these automatically before a form submits and shows a message beside the first invalid field. The CSS pseudo-classes :invalid, :valid and :user-invalid let you style fields based on their state.
Methods and properties you can call
| Member | Purpose |
|---|---|
checkValidity() | Returns true or false; on failure fires an invalid event |
reportValidity() | Same check, but also shows the browser's message to the user |
setCustomValidity(msg) | Marks the field invalid with your message; an empty string clears it |
validity | Object of booleans such as valueMissing, typeMismatch, tooShort, patternMismatch, rangeOverflow |
validationMessage | The text the browser would display |
Both check methods exist on individual fields and on the form itself, where they test every field at once.
Adding a rule HTML cannot express
Matching two password fields is a classic example. HTML has no attribute for it, but setCustomValidity plugs your own check into the same system.
const form = document.querySelector('#register');
const pass = form.elements.password;
const confirm = form.elements.confirm;
const phone = form.elements.phone;
function checkMatch() {
confirm.setCustomValidity(
confirm.value === pass.value ? '' : 'Passwords do not match.'
);
}
pass.addEventListener('input', checkMatch);
confirm.addEventListener('input', checkMatch);
phone.addEventListener('input', () => {
phone.setCustomValidity('');
if (phone.validity.patternMismatch) {
phone.setCustomValidity('Enter a 10-digit mobile number.');
}
});
form.addEventListener('submit', event => {
if (!form.reportValidity()) {
event.preventDefault();
}
});
Here the phone field would carry pattern="[0-9]{10}" in its HTML, and the code replaces the generic browser text with a clearer one.
The stuck error message
The most common bug with this API is a field that stays invalid forever. Once you call setCustomValidity('some text'), the field remains invalid until you call it again with an empty string. If your code only sets the message on failure and never clears it, the user can fix the input and still be unable to submit. Always clear first, then set only when needed, as the phone handler does.
Also remember that adding novalidate to the form turns off the automatic check on submit, but the API still works, so you can run checkValidity() yourself and display messages in your own design.
For accessibility, connect any custom error text you display to its field with aria-describedby, so screen reader users hear the message when the field is focused.
Client checks are not security
Anyone can disable JavaScript or edit the HTML in developer tools, so browser validation only improves the user experience. Always validate the same rules again on the server.
What to take away
Declare rules in HTML first, read validity to know which rule failed, use setCustomValidity for custom rules and clear it every time, and repeat validation on the server.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.