Sub topic 6
Reading validity with the Constraint Validation API
This chapter assumes you know the built-in constraint attributes (required, minlength, pattern, and so on), the input types, and how the browser shows its default error bubbles. It also assumes you can select elements and attach event listeners in JavaScript.
What the API gives you
When you add constraints to a control, the browser evaluates them continuously. The Constraint Validation API exposes the result to JavaScript. You can ask whether a field is valid, find out which rule failed, and read the message the browser would show.
Every form control (input, select, textarea) has these members:
| Member | What it returns |
|---|---|
| `validity` | A `ValidityState` object with one boolean per rule |
| `validationMessage` | The localized text the browser would display, or `""` if valid |
| `willValidate` | `false` if the control is exempt (disabled, `readonly`, `type="hidden"`, or a button) |
| `checkValidity()` | `true` or `false`, with no visible UI |
| `reportValidity()` | Same result, but also shows the browser's message and focuses the control |
<form> also has checkValidity() and reportValidity(). They test every validating control inside the form.
The ValidityState flags
Each flag matches one kind of failure. More than one can be true at a time.
| Flag | True when |
|---|---|
| `valueMissing` | A `required` field is empty |
| `typeMismatch` | The value is not a valid `email` or `url` |
| `patternMismatch` | The value does not match `pattern` |
| `tooShort` / `tooLong` | The length breaks `minlength` / `maxlength` |
| `rangeUnderflow` / `rangeOverflow` | The value is below `min` or above `max` |
| `stepMismatch` | The value does not fit `step` |
| `badInput` | The browser cannot convert the input, such as letters typed into a number field |
| `customError` | `setCustomValidity` was called with a non-empty string |
| `valid` | None of the above is true |
Reading flags to write your own messages
The browser's wording is generic. Reading the flags lets you replace it with text that fits your form. This page is complete and runnable:
<!DOCTYPE html>
<html lang="en">
<body>
<form id="demo" novalidate>
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" pattern="[a-z0-9_]+">
<p id="username-error" role="alert"></p>
<button type="submit">Save</button>
</form>
<script>
const form = document.getElementById('demo');
const username = document.getElementById('username');
const output = document.getElementById('username-error');
function messageFor(field) {
const v = field.validity;
if (v.valueMissing) return 'Choose a username.';
if (v.tooShort) return `Use at least ${field.minLength} characters.`;
if (v.patternMismatch) return 'Use lowercase letters, digits, and underscores.';
return field.validationMessage;
}
form.addEventListener('submit', (event) => {
if (!username.checkValidity()) {
event.preventDefault();
output.textContent = messageFor(username);
username.focus();
} else {
output.textContent = '';
}
});
</script>
</body>
</html>The novalidate attribute turns off the browser's own bubbles. Validation still runs, and the API still works. You are only taking over the display.
checkValidity versus reportValidity
Both methods run the same checks. Both fire an invalid event at each failing control. They differ in what the user sees.
Use checkValidity() when you draw errors yourself, or when you only need a boolean, for example to enable a Save button. Use reportValidity() when you want the native bubble from your own code, such as after a button click that is not a submit button.
Common errors
- Expecting
tooShortandtooLongon a pre-filled field. These flags only becometrueafter the user edits the value. Settinginput.valuefrom script does not trigger them. - Calling
reportValidity()in aninputhandler. It moves focus and opens a bubble on every keystroke, which interrupts typing. Validate quietly while typing and report onbluror submit. - Forgetting
willValidate. A disabled field always reportsvalid. Skip controls wherewillValidateisfalseinstead of treating them as checked. - Trusting
validas a security check. The flags describe what the browser enforced. A client can skip the browser entirely, so the server must repeat every rule.
Exercise
A field has type="number" min="18" and the user types "abc". Which ValidityState flag is true, and is rangeUnderflow also true?
Show answer
badInput is true, because the browser cannot convert "abc" to a number. rangeUnderflow is false, because there is no numeric value to compare with min. The field's valid flag is false.
Exercise
You want to enable a Save button whenever the whole form is valid, without showing any error bubbles. Which method do you call, and on which event?
Show answer
Call form.checkValidity() inside an input event listener on the form, then set button.disabled = !form.checkValidity(). checkValidity() shows no UI, so it is safe to call on every keystroke.