Sub topic 14
Custom validation with the Constraint Validation API
This chapter assumes you know the built-in validation attributes (required, pattern, min, max), how name and value work, and basic JavaScript event handling.
Why built-in attributes are not enough
Attributes cover rules that depend on one control alone. Some rules depend on other data. "Confirm password must equal password" cannot be written as an attribute. The Constraint Validation API lets your script mark a control invalid and supply the message the browser shows.
The working model
Every form control has a validity state. The browser checks it when the user submits. If any control is invalid, the browser blocks submission, focuses the first invalid control, and shows its message.
These members are the core of the API:
| Member | What it does |
|---|---|
| `validity` | A `ValidityState` object with flags such as `valueMissing`, `typeMismatch`, `patternMismatch`, `rangeUnderflow` and `customError` |
| `validationMessage` | The message the browser would show |
| `setCustomValidity(msg)` | A non-empty string marks the control invalid. An empty string clears the error |
| `checkValidity()` | Returns `true` or `false` and fires an `invalid` event on failing controls |
| `reportValidity()` | Like `checkValidity()`, but also shows the browser's message |
| `willValidate` | `false` if the control is exempt, for example if it is disabled |
A custom rule
This example flags a mismatched confirmation field.
const form = document.querySelector('form');
const password = form.elements.password;
const confirm = form.elements.confirm;
confirm.addEventListener('input', () => {
confirm.setCustomValidity(
confirm.value === password.value ? '' : 'Passwords must match'
);
});The handler runs on every edit and sets the message or clears it. Clearing matters. A control keeps its custom error until you pass an empty string, so it stays invalid even after the user fixes the value.
The password field changes too
The handler above watches only confirm. If the user edits password afterward, the confirmation field keeps a stale result. Listen on both controls and run the same check.
const form = document.querySelector('form');
const password = form.elements.password;
const confirm = form.elements.confirm;
function checkMatch() {
confirm.setCustomValidity(
confirm.value === password.value ? '' : 'Passwords must match'
);
}
password.addEventListener('input', checkMatch);
confirm.addEventListener('input', checkMatch);
checkMatch();The final call sets the initial state, so an empty form starts with a consistent result.
How the flow runs
Common errors
- Setting the message only once. The rule must run again whenever any input it depends on changes.
- Validating in the
submithandler only. By then built-in validation has already passed. Useinputorchangeso the browser can block submission itself. - Checking
validity.validand ignoringcustomError. A control with a custom message reportsvalidity.customErrorastrueandvalidity.validasfalse. - Calling
setCustomValidityon a disabled control. It is exempt from validation (willValidateisfalse), so the message has no effect.
Showing messages yourself
Call reportValidity() to show the browser's message on demand. To build your own display, listen for invalid and read validationMessage. You can also add novalidate to the form to turn off the browser's pop-ups while still using checkValidity(). The accessible error chapter covers how to present those messages.
Exercise
A user types a confirmation that does not match, then corrects it so it matches. The form still refuses to submit and the browser shows "Passwords must match". What is the likely cause, and what is the fix?
Show answer
The script set a custom message but never cleared it. A custom error stays until setCustomValidity('') is called. Run the check on every input event and pass an empty string when the values match.
Exercise
Why should a rule that compares two fields listen for input on both fields?
Show answer
The result depends on both values. If the user edits the first field after filling the second, only a handler on the first field can update the validity of the second.