The Constraint Validation API

Intermediate · 37 min

How checkValidity, reportValidity, setCustomValidity and the validity object let a script reuse the browser's own validation to show custom messages and rules.

Before thisBuilt-in Form Validation

Kevin Powell · 39 min

The Constraint Validation API

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Kevin PowellReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Every form control exposes its validation state in JavaScript: `validity` (flags such as `valueMissing` and `tooShort`), `validationMessage`, and `willValidate`. You can read the same checks the browser runs without writing your own.
  • `checkValidity()` returns true or false and fires a non-bubbling `invalid` event on each invalid control, but shows nothing and moves no focus. `reportValidity()` does the same and also shows the message and focuses the first invalid control.
  • `setCustomValidity("message")` adds a rule of your own and makes the control invalid. It stays invalid, even after the value changes, until you call `setCustomValidity("")`.
  • `form.submit()` skips validation and the `submit` event. `form.requestSubmit()` behaves like a click on a submit button: it validates, and fires the event.
  • The usual pattern for custom messages: put `novalidate` on the form, listen for `submit` and `blur`, read each control's `validity`, write your message into an element tied to the field with `aria-describedby`, and move focus to the first invalid field.

Why a script wants the browser’s validation

Built-in validation gives you the checks for free, but not the voice. The messages are the browser’s, in the browser’s language, in a bubble you cannot style. Designers want inline messages next to the field, in the site’s tone.

The tempting answer is to write your own validation from scratch. The better answer is to keep the browser’s checks and replace only the display. The browser already knows how to decide that an email is malformed or a field is empty. The constraint validation API exposes that knowledge to JavaScript, so you ask the browser “is this valid, and why not?” and then show your own message.

What each control exposes

Every form control has these:

  • validity: an object of boolean flags such as valueMissing, typeMismatch, patternMismatch, tooShort, tooLong, rangeUnderflow, rangeOverflow, stepMismatch, badInput, customError, plus valid.
  • validationMessage: the browser’s own message for the current problem, or an empty string.
  • willValidate: whether the control is validated at all.
  • checkValidity(), reportValidity() and setCustomValidity().

The flags are what make custom messages possible. Instead of one generic “invalid”, you can write one message for valueMissing (“Tell us your name”), another for typeMismatch (“That does not look like an email”).

checkValidity and reportValidity

checkValidity() asks the question quietly. It returns true or false, and for each invalid control it fires an invalid event. reportValidity() asks, then reports: the browser shows its message bubble and focuses the first invalid control.

I tested both on a form with two empty required fields. Both returned false, and invalid fired on both fields (and, as the spec says, the event does not bubble, so a listener on the form never sees it; you attach listeners to the controls or use the capture phase). After checkValidity(), document.activeElement was still the body. After reportValidity() it was the first invalid field. This matched in Chromium, Firefox and WebKit.

Use checkValidity() to enable or disable a button as the user types, or to run validation before a custom submit. Use reportValidity() when you want the native bubble on demand.

setCustomValidity

setCustomValidity("message") makes a control invalid with your message. Passing an empty string clears it. This is how you add a rule the browser does not know, such as “passwords must match” or “that username is taken”.

confirm.addEventListener("input", () => {
  confirm.setCustomValidity(
    confirm.value === password.value ? "" : "Passwords do not match"
  );
});

The empty string matters, and it is the usual bug. A custom message stays until you clear it. In a test, I set a custom message on an email field, then changed the value to a different valid address. validity.customError was still true. A handler that sets the message but never clears it leaves the user stuck. Always run the clear path when the value is acceptable.

Two other details from tests: after setCustomValidity("Use your work email"), validationMessage returned that text; and a disabled control with a custom message still reported checkValidity() as true, since willValidate was false.

submit versus requestSubmit

Scripts often submit a form themselves. There are two methods, and they differ.

form.submit() sends the form immediately. It does not run validation and does not fire a submit event. In a test, a form with two empty required fields navigated to its action, and no submit listener ran. Anything that relied on a listener to validate was bypassed.

form.requestSubmit() acts like clicking a submit button. It runs validation, fires submit, and sends the form only if it passed. In the same test it fired no submit event while fields were invalid, and one once they were filled. With novalidate set on the form, it submitted despite empty required fields. requestSubmit() has been in Chrome since 76, Firefox 75 and Safari 16 according to the compatibility data (BCD 8.1.10), so it is safe to rely on.

The custom message pattern

A typical replacement for the browser’s bubbles looks like this:

  1. Put novalidate on the form, so the browser does not show its bubble.
  2. On submit, loop over the controls, read validity and look for problems.
  3. For each problem, write a message into an element next to the field, and link it to the input with aria-describedby. Setting aria-invalid="true" on the input is also common.
  4. Move focus to the first invalid field.
  5. Also check on blur, and clear the message when the user fixes the problem.

Because the error message appears dynamically, screen readers will not announce it unless you tell them. An aria-live="polite" region, or focusing the field so its description is read, handles that. The accessible names and descriptions lesson covers aria-describedby.

None of this replaces server-side validation. Treat the client code as a convenience; a script can be bypassed.

What the video covers

The embed is a clip, 0:00 to 36:40, from Kevin Powell’s “How to set custom error messages for your HTML forms” (September 2025), a 39-minute build on a Frontend Mentor form. The chapter list for the clip covers using novalidate and checking validity manually, checking all the form fields, adding error messages, removing empty error elements, styling the error states, aria-live="polite", custom text per error, radio button errors, adding errors when the user leaves a field, removing errors when fixed and moving focus to the first invalid element. The clip ends where the final chapter, fixing the layout when error messages appear, begins: that part is CSS. I could not read a transcript, so I do not describe the code. The runner-up is Steve Griffith’s older, API-first walkthrough. The test results in this lesson, including checkValidity() against reportValidity(), persisting custom messages and submit() against requestSubmit(), ran in headless Chromium, Firefox and WebKit. I could not test how a screen reader announces the messages.

Where this fits

This follows built-in form validation. The next lesson, autocomplete and input modes, is about helping the user fill the form in. For scripting forms more generally, see DOM manipulation and events.

Check yourself

  1. 01What is the difference between `form.checkValidity()` and `form.reportValidity()`?

    Both return whether the form is valid and fire an `invalid` event on each invalid control. `reportValidity()` also shows the browser's message and focuses the first invalid control. In a test, `checkValidity()` left focus on the body and `reportValidity()` moved it to the first invalid field.

  2. 02You call `email.setCustomValidity("Use your work email")` in an input handler. The user corrects the address, but the form still will not submit. Why?

    A custom validity message stays until you clear it. Changing the value does not clear it. Call `setCustomValidity("")` when the value passes your rule. In a test, the control still had `customError` set after its value changed.

  3. 03Why might a script that validates its form by calling `form.submit()` let invalid data through?

    `form.submit()` sends the form without running validation and without firing a `submit` event. In a test, invalid fields were sent and no submit handler ran. Use `form.requestSubmit()`, which validates and fires the event.

  4. 04What does `willValidate` tell you, and why does it matter for a disabled field?

    `willValidate` is `false` for controls the browser never validates, such as disabled, readonly and hidden inputs. So a disabled control reports `checkValidity()` as true even after `setCustomValidity` was called on it, though `validity.customError` still reads true.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark