Sub topic 14
Custom validation with the Constraint Validation API
This chapter assumes you know the built-in validation attributes (required, pattern, min, max), the submit event, and basic DOM scripting. The Constraint Validation API is the set of properties, methods, and events that lets JavaScript read the browser's validation state and add rules the attributes cannot express.
What the API exposes
Every form control that can be validated (input, select, textarea, button, output, fieldset) has the same members.
| Member | Type | Purpose |
|---|---|---|
| `validity` | `ValidityState` | Object of boolean flags describing why the control is invalid |
| `validationMessage` | string | The message the browser would show, or an empty string |
| `willValidate` | boolean | `false` if the control is exempt from validation |
| `checkValidity()` | method | Returns `true` or `false` and fires an `invalid` event on failure. It shows no message. |
| `reportValidity()` | method | Same check, and also shows the browser's message bubble |
| `setCustomValidity(msg)` | method | Marks the control invalid with `msg`, or valid if `msg` is empty |
The form element has checkValidity() and reportValidity() too. They check every control in the form.
The ValidityState flags
validity tells you which rule failed. Each flag matches a source of invalidity.
| Flag | Becomes `true` when |
|---|---|
| `valueMissing` | A `required` control is empty |
| `typeMismatch` | The value does not fit `type="email"` or `type="url"` |
| `patternMismatch` | The value does not match `pattern` |
| `tooShort` / `tooLong` | The value breaks `minlength` or `maxlength` |
| `rangeUnderflow` / `rangeOverflow` | The value is below `min` or above `max` |
| `stepMismatch` | The value does not land on a `step` increment |
| `badInput` | The browser cannot convert the input, such as letters typed into a number field |
| `customError` | `setCustomValidity` was called with a non-empty message |
| `valid` | None of the other flags is `true` |
A control can have several flags set at once. Because validationMessage returns only one message, check the flags yourself when you want to control the wording.
Setting a custom error
The call setCustomValidity('some text') does two things. It sets validity.customError to true, and it makes validationMessage return that text. While the message is non-empty, the control stays invalid and blocks submission.
The most common mistake is forgetting to clear the message. If you set an error and never reset it to '', the field stays invalid even after the user fixes the value.
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);This version listens on both fields. If you listen only on confirm, a user who edits password afterward leaves a stale result on confirm.
The validation lifecycle
The diagram shows what happens when the user submits and how your code takes part.
Your input handlers keep the custom state current, so the browser's check at submit time sees the right result. The submit event only fires when every control passes, so your submit handler does not need to repeat the checks.
Mapping built-in errors to your own messages
The browser's default messages vary between browsers and languages. To control the wording, read the flags and call setCustomValidity with your own text.
<form id="signup" 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">Sign up</button>
</form>
<script>
const form = document.getElementById('signup');
const username = form.elements.username;
const errorBox = document.getElementById('username-error');
function messageFor(input) {
const v = input.validity;
if (v.valueMissing) return 'Choose a username.';
if (v.tooShort) return 'Use at least ' + input.minLength + ' characters.';
if (v.patternMismatch) return 'Use lowercase letters, digits, and underscores only.';
return '';
}
function update() {
// Clear any earlier custom error so the built-in flags are accurate.
username.setCustomValidity('');
username.setCustomValidity(messageFor(username));
errorBox.textContent = username.validationMessage;
}
username.addEventListener('input', update);
form.addEventListener('submit', (event) => {
update();
if (!form.checkValidity()) {
event.preventDefault();
username.focus();
}
});
</script>Three details in this example matter.
novalidateon the form turns off the browser's automatic blocking and message bubbles, so your script owns the user interface. Thesubmitevent now fires even when controls are invalid, which is why the handler callscheckValidity()itself.- Calling
setCustomValidity('')first resetscustomError. Without it, an earlier custom message would not matter for the flags, but it would keep the field invalid after the built-in problem is fixed. - Once a custom message is set,
validationMessagereturns your message. When the message is empty and a built-in rule fails, it returns the browser's default text.
The invalid event
When checkValidity() or a submit attempt finds an invalid control, the browser fires an invalid event on that control. This event does not bubble, so you cannot catch it with one listener on the form. Use the capture phase, or attach a listener to each control.
form.addEventListener('invalid', (event) => {
event.preventDefault(); // suppress the browser's message bubble
const field = event.target;
field.setAttribute('aria-invalid', 'true');
}, true);Calling preventDefault() on invalid suppresses the built-in message bubble but still blocks submission. This is a useful middle path: you keep the browser's checking and draw your own messages.
Validation that depends on other data
Cross-field rules, such as "end date after start date", fit the same pattern. Write one function that recomputes the error from the current values and call it from every input handler involved.
For asynchronous rules, such as "is this username taken?", set a pending error first and clear it when the answer arrives.
let latest = 0;
username.addEventListener('input', async () => {
const ticket = ++latest;
username.setCustomValidity('Checking availability...');
const response = await fetch('/api/username?name=' + encodeURIComponent(username.value));
const { taken } = await response.json();
if (ticket !== latest) return; // a newer keystroke superseded this request
username.setCustomValidity(taken ? 'That username is taken' : '');
});The ticket counter discards stale responses. Without it, a slow response for an old value could overwrite the result for the current value. The pending message also blocks submission until the check finishes. Keep in mind that client-side checks can be bypassed, so the server must repeat any rule that matters.
Gotchas and edge cases
- Exempt controls. A control is barred from validation, and
willValidateisfalse, if it isdisabled,readonly,type="hidden", or inside adatalist. A custom error on such a control does not block submission. tooShortandtooLongneed user edits. Settinginput.valuefrom a script does not trigger these flags.required,pattern, and type checks do apply to programmatic values.checkValidity()versusreportValidity(). UsecheckValidity()for silent checks, such as enabling a button. UsereportValidity()when you want the user to see the message and have focus move to the first problem.formnovalidate. A submit button with this attribute skips validation for that submission only. Use it for a "Save draft" button.- Radio groups. If any radio in a group has
required, the group is invalid until one is selected. Set custom errors on one member only, usually the first. - Message language. Built-in messages follow the browser's language, not the page's. Mapping flags to your own text is the only way to guarantee consistent wording.
Exercises
Exercise
A form uses novalidate. A user types an invalid email address and presses submit. Does the submit event fire, and what must your handler do to stop the data from being sent?
Show answer
Yes, the event fires, because novalidate disables the browser's blocking. The handler must call form.checkValidity() (or reportValidity()) and, if it returns false, call event.preventDefault().
Exercise
You wrote end.addEventListener('input', () => end.setCustomValidity(end.value >= start.value ? '' : 'End must be after start')). A user fixes the start date afterward, but the end field stays invalid. Why, and how do you fix it?
Show answer
The check runs only when the end field changes, so the error from the earlier comparison stays set after the start date changes. Move the logic into one function and call it from the input handlers of both the start and end fields.
Exercise
Which validity flag is true after setCustomValidity('Nope'), and which method call makes the control valid again?
Show answer
validity.customError is true. Calling setCustomValidity('') clears it, and the control becomes valid if no built-in rule also fails.