How to Validate a Form With the Constraint Validation API
Validate a form with the Constraint Validation API: validity states, setCustomValidity, checkValidity, reportValidity, custom messages and accessible errors.

Browsers already know how to validate forms. Put required on an input and the form refuses to submit an empty value; set type="email" and it checks the shape of an address; add minlength or pattern and the rules grow. All of this is exposed to JavaScript through the Constraint Validation API, which lets you ask whether a field is valid, learn why it is not, add your own rules and show errors in your own style, while keeping the browser's behavior for keyboards, screen readers and password managers. Most hand-written validation libraries rebuild what this API provides. This guide shows how to validate a form with the Constraint Validation API in JavaScript: the built-in attributes, the validity object and its flags, checkValidity() and reportValidity(), custom rules with setCustomValidity(), replacing the default bubbles with accessible inline messages, validating on blur and on submit, cross-field checks, styling with :user-invalid, the limits of client-side checks and testing. The API is documented on MDN and works in all current browsers.
Rules from HTML attributes
Most rules need no script. The attributes below declare what a valid value looks like, and the browser enforces them when the form is submitted.
<form id="signup" novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<label for="age">Age</label>
<input id="age" name="age" type="number" min="18" max="120" required>
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+" title="Lowercase letters, numbers and underscores">
<button>Create account</button>
</form>(three fields with declared rules; novalidate lets script show the messages)required, type (such as email, url, number), min, max, step, minlength, maxlength and pattern are the available constraints. The novalidate attribute on the form turns off the browser's own pop-up bubbles on submit, so you can present errors yourself, while the validation logic still runs and is available to script. Leave it off if the default bubbles are good enough for your site.
The validity object
Every form control has a validity property that explains the current state with boolean flags: valueMissing, typeMismatch, patternMismatch, tooShort, tooLong, rangeUnderflow, rangeOverflow, stepMismatch, badInput, customError and the summary valid.
const email = document.querySelector("#email");
email.value = "not-an-email";
console.log(email.validity.typeMismatch);
console.log(email.validity.valid);
console.log(email.validationMessage);
email.value = "[email protected]";
console.log(email.validity.valid);true
false
Please include an '@' in the email address. 'not-an-email' is missing an '@'.
truevalidationMessage holds the browser's own explanation, in the user's language, which is good enough when you are content with its wording. For fields with several rules, the flags tell you which one failed so that you can write a specific message. Note that tooShort and tooLong become true only after the user edits the value, not when a script sets it, which is a documented quirk.
checkValidity and reportValidity
checkValidity() returns a boolean without showing anything, and fires an invalid event on each failing control. reportValidity() does the same and also displays the browser's message on the first invalid field and focuses it. Both exist on controls and on the form, where they check every control.
const form = document.querySelector("#signup");
form.addEventListener("submit", (event) => {
if (!form.checkValidity()) {
event.preventDefault();
console.log("form has errors");
return;
}
console.log("submitting");
});form has errorsWith novalidate, the browser does not block the submission, so the handler must check and stop it, as shown. Without novalidate, the browser blocks the submit itself and shows its bubble, and the submit event does not fire for an invalid form.
Custom rules with setCustomValidity
When a rule cannot be written as an attribute, set your own message with setCustomValidity(). A non-empty string marks the control invalid and becomes the validationMessage; an empty string clears the error. You must clear it explicitly, or the control stays invalid forever.
const username = document.querySelector("#username");
const reserved = ["admin", "root", "support"];
username.addEventListener("input", () => {
if (reserved.includes(username.value.toLowerCase())) {
username.setCustomValidity("That username is reserved.");
} else {
username.setCustomValidity("");
}
});
username.value = "admin";
username.dispatchEvent(new Event("input"));
console.log(username.validity.customError, username.validationMessage);true That username is reserved.This is the right place for rules the browser cannot know: reserved names, a password strength check, a date that must be in the future. For checks that need the server, such as whether a username is taken, set a custom error when the response arrives, and clear it as soon as the user edits the field.
Cross-field rules
A rule that compares fields, such as password confirmation, can run on input of either field and set the message on the one the user will fix.
const password = document.querySelector("#password");
const confirm = document.querySelector("#confirm");
function checkMatch() {
confirm.setCustomValidity(
confirm.value && confirm.value !== password.value ? "Passwords do not match." : "",
);
}
password.addEventListener("input", checkMatch);
confirm.addEventListener("input", checkMatch);(the confirmation field is invalid while the two values differ)Calling checkMatch() from both fields keeps the error current when the first password is edited after the confirmation was typed.
Show errors inline and accessibly
The default bubbles disappear quickly and are hard to style. A better design places the message next to the field, connects it with aria-describedby and marks the field with aria-invalid, so a screen reader announces it with the field. Replace the bubbles by listening to the invalid event and calling preventDefault() on it.
<label for="email">Email</label>
<input id="email" name="email" type="email" required aria-describedby="email-error">
<p id="email-error" class="error" hidden></p>const form = document.querySelector("#signup");
function showError(field) {
const error = document.getElementById(field.getAttribute("aria-describedby"));
if (!error) return;
if (field.validity.valid) {
error.hidden = true;
error.textContent = "";
field.removeAttribute("aria-invalid");
} else {
error.hidden = false;
error.textContent = field.validationMessage;
field.setAttribute("aria-invalid", "true");
}
}
form.addEventListener(
"invalid",
(event) => {
event.preventDefault();
showError(event.target);
},
true,
);
form.addEventListener("input", (event) => {
if (event.target.matches("input, select, textarea")) showError(event.target);
});
form.addEventListener("submit", (event) => {
if (!form.checkValidity()) {
event.preventDefault();
form.querySelector(":invalid")?.focus();
}
});(errors appear under each field, tied to it for assistive technology, and focus moves to the first problem)The invalid event does not bubble, so the listener uses the capture phase to see it on the form. Moving focus to the first invalid field after a failed submit is what a native bubble would have done. For a long form, add a summary at the top that links to each error.
Better messages
validationMessage is localized but generic. Replace it with specific text based on the flags.
function messageFor(field) {
const v = field.validity;
if (v.valueMissing) return `Enter your ${field.labels[0].textContent.toLowerCase()}.`;
if (v.typeMismatch && field.type === "email") return "Enter an email like [email protected].";
if (v.tooShort) return `Use at least ${field.minLength} characters.`;
if (v.rangeUnderflow) return `The minimum is ${field.min}.`;
if (v.patternMismatch) return field.title || "Use the requested format.";
return field.validationMessage;
}Enter an email like [email protected].Write messages that say how to fix the problem, not only what is wrong. If you translate your site, produce them from your own translation table, since overriding the browser's message loses its automatic localization.
When to validate
Validating every field on every keystroke interrupts people who are still typing, and showing "invalid email" after the first character is hostile. A good rhythm is to validate on blur, when the user leaves the field, and re-validate on input only once the field has been marked invalid, so the message disappears as soon as it is fixed. On submit, validate everything. CSS has a helpful pseudo-class: :user-invalid matches an invalid control only after the user has interacted with it, which avoids showing red borders on a fresh form, and it is supported by current browsers.
input:user-invalid {
border-color: #b42318;
}
input:user-valid {
border-color: #027a48;
}
.error {
color: #b42318;
font-size: 0.875rem;
}(fields are outlined red or green only after the user has touched them)Do not rely on color alone to show an error; the text message and the aria-invalid attribute carry the meaning.
Skip validation for some buttons
A "Save draft" button should submit without validating. Put formnovalidate on it.
<button type="submit" formnovalidate name="intent" value="draft">Save draft</button>
<button type="submit" name="intent" value="publish">Publish</button>(the first button submits even when fields are invalid)Limits
Client-side validation is a convenience for the user and no protection for the server. Anyone can send a request without your form, so every rule must be enforced again on the server, with the same or stricter checks. The built-in email check is deliberately loose, since a strict check rejects valid addresses; the only real test of an address is sending a message to it. The pattern attribute uses a regular expression that must match the whole value and is compiled with the v flag in current browsers, so test patterns carefully. And custom controls built from div elements do not take part in validation, which is another reason to use real form elements.
Test it
Submit the form empty, with each field invalid in turn and with all valid, and check the messages, focus and the aria-invalid attributes. Test with a keyboard only and with a screen reader, to be sure the error is announced when the field receives focus. In automated tests, set values and call form.checkValidity() or read validity flags directly, which needs no real browser interaction.
email.value = "";
console.log(email.validity.valueMissing);
email.value = "[email protected]";
console.log(form.checkValidity());true
falseThe second result is false in this example because the other fields are still empty, which shows that form.checkValidity() considers every control.


