Sub topic 6
Reading validity with the Constraint Validation API
This chapter assumes you know HTML form controls and labels, how to select elements and handle events in JavaScript, and the built-in constraint attributes (required, minlength, pattern, min, max, step) and input types such as email and number. Here you will learn how to read the result of those checks from JavaScript.
What the API is
The browser evaluates constraints on its own. The Constraint Validation API lets your code read the results and ask for the checks to run again. It is a set of properties and methods on form controls (input, select, textarea, button, fieldset, output, object) and on the form element.
| Member | On | What it gives you |
|---|---|---|
| `willValidate` | control | `true` if the control takes part in validation |
| `validity` | control | A `ValidityState` object with one boolean per kind of failure |
| `validationMessage` | control | The text the browser would show, or `""` if the control is valid |
| `checkValidity()` | control, form | Returns `true` or `false`. Fires an `invalid` event on each failing control |
| `reportValidity()` | control, form | Same check, and also shows the browser's error bubble |
| `setCustomValidity(msg)` | control | Sets or clears a custom error (covered in a later chapter) |
willValidate: who is checked at all
A control is barred from validation, so willValidate is false, in these cases:
- It is
disabled. - It is
readonly. - It has
type="hidden", or it is a button of typeresetorbutton. - It has a
datalistancestor. - It is
output,object, orfieldset, which have no value to check.
A barred control never blocks submission, even if it carries required. Loops over form.elements should skip such controls, as the loop in the later error-rendering example does.
The ValidityState object
field.validity returns a live ValidityState. Each property is a boolean, and valid is true only when every other flag is false.
| Flag | Becomes `true` when |
|---|---|
| `valueMissing` | A required field is empty, a required checkbox is unchecked, or no radio in a required group is selected |
| `typeMismatch` | The value is not a valid `email` or `url` |
| `patternMismatch` | A non-empty value does not match `pattern` |
| `tooShort` | The value is shorter than `minlength` |
| `tooLong` | The value is longer than `maxlength` |
| `rangeUnderflow` | The value is below `min` |
| `rangeOverflow` | The value is above `max` |
| `stepMismatch` | The value does not fit the `step` grid |
| `badInput` | The browser cannot convert what the user typed, such as `1e` in a number field |
| `customError` | `setCustomValidity` was called with a non-empty string |
| `valid` | None of the above |
Several flags can be true at once. A value can be both tooShort and patternMismatch. The validationMessage text normally describes only one of them.
Try it
Save this as one file and open it. Type into the field and watch the console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validity demo</title>
</head>
<body>
<form id="demo">
<label for="qty">Quantity (multiples of 5, 5 to 50)</label>
<input id="qty" name="qty" type="number" min="5" max="50" step="5" required>
<button type="submit">Order</button>
</form>
<script>
const qty = document.getElementById('qty');
qty.addEventListener('input', () => {
const v = qty.validity;
console.log({
valueMissing: v.valueMissing,
badInput: v.badInput,
rangeUnderflow: v.rangeUnderflow,
rangeOverflow: v.rangeOverflow,
stepMismatch: v.stepMismatch,
valid: v.valid,
message: qty.validationMessage
});
});
</script>
</body>
</html>Typing 7 gives stepMismatch: true. Typing 60 gives rangeOverflow: true. Clearing the field gives valueMissing: true.
Edge cases that surprise people
- Empty values skip most checks.
typeMismatch,patternMismatch, and the range flags only apply to a non-empty value. An empty optionaltype="email"field is valid. Addrequiredif you want to reject emptiness. tooShortandtooLongdepend on user edits. Browsers only flag them after the user has changed the value. A value set by your script or by a defaultvalueattribute can be shorter thanminlengthand still count as valid.maxlengthnormally stops the user from typing too much, sotooLongmostly appears for script-set values.badInputhides other flags. If the user types text the control cannot parse,field.valueis an empty string. You may seebadInputtogether withvalueMissing. CheckbadInputfirst when you pick a message.- A
patternis anchored. The browser treats it as^(?:pattern)$, so you do not add the anchors yourself. - Radio groups are checked as a group.
valueMissingistrueon every radio in a required group until one is selected. validationMessageis localized. Its wording depends on the browser and the user's language. Do not compare it to a fixed string in code or tests. Test thevalidityflags instead.
checkValidity versus reportValidity
Both methods run the checks and return a boolean. They differ in what they do on failure.
checkValidity()is silent for the user. It fires aninvalidevent at each failing control and returnsfalse.reportValidity()does the same, and also shows the browser's error bubble on the first invalid control and focuses it.
The same two methods exist on the form. form.checkValidity() tests every control that has willValidate set to true and returns true only if all pass.
Use checkValidity() to enable or disable a button, or to update a progress hint, because it makes no visible noise. Use reportValidity() when you want the browser's own message, for example after a custom "Next step" button.
const form = document.getElementById('signup');
const next = document.getElementById('next');
next.addEventListener('click', () => {
if (form.reportValidity()) {
showStepTwo();
}
});
function showStepTwo() {
document.getElementById('step-two').hidden = false;
}Calling form.requestSubmit() instead of form.submit() runs validation and fires the submit event. form.submit() skips both.
The invalid event
When a check fails, the browser fires an invalid event on the control. This event does not bubble, so a listener on the form only receives it if you register it in the capture phase. Calling preventDefault() on it suppresses the browser's bubble, so you can show your own message.
const form = document.getElementById('signup');
form.addEventListener(
'invalid',
(event) => {
event.preventDefault();
const field = event.target;
const error = document.getElementById(`${field.id}-error`);
if (error) error.textContent = field.validationMessage;
},
true
);The true as the third argument selects the capture phase. Without it, this listener never runs.
Where validation sits in submission
On a submit attempt, the browser runs this sequence. A failure stops it before any network request.
Note that the submit event only fires after built-in validation passes. When you set form.noValidate = true, built-in checks no longer block submission, so your own submit handler must read the validity and decide.
Turning flags into your own messages
Browser messages differ between vendors and are often vague. A helper that maps flags to text gives consistent wording. This one reads the same properties you saw above.
function messageFor(field) {
const v = field.validity;
if (v.valid) return '';
if (v.customError) return field.validationMessage;
if (v.badInput) return 'Enter a number, using digits only.';
if (v.valueMissing) return 'This field is required.';
if (v.typeMismatch) return `Enter a valid ${field.type}.`;
if (v.tooShort) return `Use at least ${field.minLength} characters.`;
if (v.tooLong) return `Use at most ${field.maxLength} characters.`;
if (v.rangeUnderflow) return `Value must be ${field.min} or more.`;
if (v.rangeOverflow) return `Value must be ${field.max} or less.`;
if (v.stepMismatch) return `Value must be a multiple of ${field.step}.`;
if (v.patternMismatch) return field.title || 'Use the requested format.';
return field.validationMessage;
}
function showErrors(form) {
let first = null;
for (const field of form.elements) {
if (!field.willValidate) continue;
const text = messageFor(field);
const slot = document.getElementById(`${field.id}-error`);
if (slot) slot.textContent = text;
if (text && !first) first = field;
}
return first;
}The order of the checks is a choice. Putting customError first means a message you set with setCustomValidity always wins. Putting badInput before valueMissing avoids telling a user their half-typed number is "required".
Common mistakes
- Reading
validityonce and caching it. The object is live, but a copy you made of its values is not. Read the flags again inside the handler that needs them. - Listening for
invalidon the form without capture. The listener never runs, because the event does not bubble. - Treating
valid: trueas "safe". It only means the browser's checks passed on the client. A script,curl, or a modified page can skip every one of them, so the server must check again. - Forgetting
willValidate. Showing an error for a disabled field confuses users, because the browser would not have blocked submission for it. - Testing
validationMessagestrings. They change by browser and locale. Compare flags instead.
Exercise
A form has <input id="code" name="code" pattern="[A-Z]{4}" maxlength="4"> with no required attribute. The user leaves it empty. What are code.validity.valid and code.validity.patternMismatch, and what happens if you call form.checkValidity() when this is the only field? Then the user types ab. Which flag changes, and what does checkValidity() return?
Show answer
With an empty value, valid is true and patternMismatch is false, because pattern only applies to non-empty values. form.checkValidity() returns true and no invalid event fires. After the user types ab, patternMismatch becomes true (the value does not match four uppercase letters), valid becomes false, and checkValidity() returns false and fires an invalid event on the field. tooShort stays false because there is no minlength.
Exercise
You attach form.addEventListener('invalid', handler) to show custom messages, but the handler never runs when a field fails. What is the cause and the fix?
Show answer
The invalid event does not bubble, so a bubbling-phase listener on the form never receives it from a child control. Register the listener in the capture phase with form.addEventListener('invalid', handler, true), or attach the listener to each control.