completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Validation

Learn web components form validation with setValidity(): flags, messages, the anchor, reportValidity(), :invalid, and required or min checked by hand.

By the end, you can
  • 01
    Report a problemRaise validity flags with a message using setValidity(), and clear them again with {}.
  • 02
    Point the browser at itChoose an anchor so the message and focus land on the right part, and say which controls a form checks.
  • 03
    Show it at the right timeShow an error only after the person has tried, with a custom state, and make the message reach screen readers.

How do web components validate form input?

Leaf and Kettle's kitchen makes at most six cups per order. A plain number box can say so. Give it max="6", and Chrome won't send a form with 7 in it. It shows a small message instead: Value must be less than or equal to 6.

Ravi's tea-cups from lesson 16.1 sends anything. Yesterday Asha ordered nine cups, and the kitchen had to call her back. How does a custom element say "this isn't right"?

A form-associated custom element reports a problem with setValidity() on its internals. It passes flags that say what's wrong, and a message in words. Then the form treats it like an invalid input. It won't send, the host matches :invalid, and the browser shows the message.

Here is tea-cups with a limit. Its class is in the tea-cups.js tab:

An order form with a limit on the cupsPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-cups name="cups"></tea-cups>  <button>Order</button></form><script src="tea-cups.js"></script><script>  const form = document.querySelector("#order");  form.querySelector("tea-cups").addEventListener("invalid", () => {    console.log("Not sent: the form found a problem.");  });  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new FormData(form).get("cups"), "cups");  });</script>
ResultLoading…
tea-cups.js: more than six cups is a problemJavaScript
class TeaCups extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();
  #cups = 6;

  constructor() {
    super();
    this.attachShadow({ mode: "open", delegatesFocus: true }).innerHTML =
      "<output>6</output> <button>+</button>";
    this.#internals.setFormValue("6");
    this.shadowRoot.querySelector("button").addEventListener("click", () => {
      this.#cups++;
      this.shadowRoot.querySelector("output").textContent = this.#cups;
      this.#internals.setFormValue(String(this.#cups));
      if (this.#cups > 6) {
        this.#internals.setValidity({ rangeOverflow: true }, "Pick at most 6 cups.");
      } else {
        this.#internals.setValidity({});
      }
    });
  }
}
customElements.define("tea-cups", TeaCups);
  • On the page, line 2 is tea-cups. Line 3 is the Order button.
  • Line 8 listens for an invalid event on tea-cups. The form fires it when it finds a problem. Lines 11 to 14 print what the form would send.
  • In the tab, lines 2 and 3 make the class form-associated and get its internals, as in lesson 16.1. Line 8 delegates focus, as lesson 9.3 showed.
  • Line 14 hands the form the number on every click, as lesson 16.2 taught.
  • Line 16 runs when there are more than 6 cups. It calls setValidity() with a flag, rangeOverflow, and a message.
  • Line 18 passes an empty object. That clears the problem.

Press Order. It prints Sent: 6 cups. Now press + once, so the box says 7, and press Order again. It prints Not sent: the form found a problem. The form didn't send. Chrome showed Pick at most 6 cups. next to the cups, and moved focus to the + button.

A card at the top: setValidity({ rangeOverflow: true }, "Pick at most 6 cups."). Three arrows lead down to three cards. Flags: rangeOverflow: true, which makes it invalid. Message: Pick at most 6 cups., the words the person sees. Anchor, left out: the host, tea-cups, where focus and the message go.setValidity({ rangeOverflow: true }, "Pick at most 6 cups.")flagsmessageanchor, left outrangeOverflow: truePick at most 6 cups.the host, tea-cupsmakes it invalidthe words people seewhere focus goes
One call fills three things. The flags say what's wrong, and the message says it in words. The anchor says where. Line 16 leaves it out, so it's the host.
Real-life analogyA repair slip on a library book

Meena helps at the library on Sundays. A returned book with a torn page gets a repair slip. The slip has boxes to tick, like Torn page or Missing cover. It also has a line for a note: Page 12 is torn. A book with a slip stays behind the desk. Nobody can borrow it until the slip comes off.

In real life: The boxes on the slip: Torn page, Missing cover
In JavaScript: The flags, like rangeOverflow
In real life: The note in Meena's own words
In JavaScript: The message, Pick at most 6 cups.
In real life: A book with a slip can't be borrowed
In JavaScript: An invalid element stops the form
In real life: Taking the slip off
In JavaScript: setValidity({})
The main idea

Tell the form what's wrong with setValidity(flags, message). Do it every time the value changes. Pass {} when nothing is wrong. The form then checks your element like an input.

Why it matters: the browser can't see inside your element. It knows a value is bad only when you say so.

setValidity() works in Chrome 77, Firefox 98, and Safari 16.4 and later. Like the rest of form association, it's Baseline widely available on web-features.

What does setValidity() do?

setValidity() takes three things, as MDN lists them:

  • flags: an object of true and false values. Each one names a kind of problem.
  • a message: the words for the person.
  • an anchor: the element the message points at. The next section covers it.

There are ten flags. They're the ten an input's validity has, as the JavaScript lesson showed in the validity checklist. An input sets them itself. Your element sets them by hand. Read each row across:

The ten validity flags
FlagWhen an input raises itWhen your element might raise it
valueMissingIt's required and has no value.Nothing is picked, like a blend with no tea ticked.
typeMismatchAn email or URL box holds text that isn't one.It wants an email address and gets something else.
patternMismatchThe value doesn't match its pattern.A gift code isn't LK- and four digits.
tooLongThe person typed past maxlength.A note is longer than you allow.
tooShortThe person typed less than minlength.A name is shorter than you allow.
rangeUnderflowA number is below min.Fewer cups than the smallest order.
rangeOverflowA number is above max.More cups than the kitchen can make.
stepMismatchA number isn't a whole number of steps from min.Grams that aren't in 5 g steps.
badInputThe browser can't read what was typed, like letters in a number box.It can't read what was typed, like fifty in a grams box.
customErrorsetCustomValidity() set a message.Any other rule, like a closed kitchen.

customError is for a rule no other flag fits. An input gets it from setCustomValidity(). Your element just sets it.

Now try a second call on an element that already has a problem. Line 8 sets rangeOverflow. Only line 10 changes:

Playground: what does a second call leave?
An element with one problem, then a second setValidity() callPop out in the code editor (opens in a new tab)HTML
<tea-cups></tea-cups><script>  customElements.define("tea-cups", class extends HTMLElement {    static formAssociated = true;    internals = this.attachInternals();  });  const cups = document.querySelector("tea-cups");  cups.internals.setValidity({ rangeOverflow: true }, "Pick at most 6 cups.");  try {    cups.internals.setValidity({});  } catch (error) {    console.log(`${error.name}: ${error.message}`);  }  const flags = ["valueMissing", "typeMismatch", "patternMismatch", "tooLong", "tooShort",    "rangeUnderflow", "rangeOverflow", "stepMismatch", "badInput", "customError"];  console.log("Flags:", flags.filter((flag) => cups.internals.validity[flag]).join(", ") || "none");  console.log("Message:", JSON.stringify(cups.internals.validationMessage));  console.log("Matches :invalid:", cups.matches(":invalid"));</script>
ResultLoading…
Try it yourself
An empty object clears every flag

Every flag you leave out counts as false. So {} sets all ten to false, and the message becomes empty. The element is valid again.

Only line 10 changes. Line 8 always sets rangeOverflow first.
  • Line 8 makes the cups invalid, with a message. Line 10 is the second call.
  • If line 10 throws, line 12 prints the error.
  • Lines 14 and 15 list the ten flags. Line 16 prints the true ones.
  • Line 17 prints the message, in quotes. Line 18 asks if the host matches :invalid.
  • {}: Flags: none and an empty message. The cups are valid again.
  • stepMismatch: only stepMismatch. rangeOverflow is gone.
  • Two flags: both are true, with one message.
  • customError: Flags: customError, with the kitchen's message.
  • No message: a TypeError. The first call's flag and message are still there.
  • A false flag: no flags, and an empty message. The words were dropped.

So each call replaces every flag. A flag you leave out is false. A message counts only while a flag is true. And a true flag with no message throws. The HTML Standard's steps say each of these. Here is the throw in Chrome's setValidity(). You don't need to know C++ to follow it:

How Chrome checks the message and the anchor, shortened from element_internals.cc lines 186 to 222C++
void ElementInternals::setValidity(ValidityStateFlags* flags,                                   const String& message,                                   HTMLElement* anchor,                                   ExceptionState& exception_state) {  // ...  if (!IsValidityStateFlagsValid(flags) && message.empty()) {    exception_state.ThrowTypeError(        "The second argument should not be empty if one or more flags in the "        "first argument are true.");    return;  }   if (!anchor) {    anchor = &Target();  } else if (!Target().IsShadowIncludingInclusiveAncestorOf(*anchor)) {    exception_state.ThrowDOMException(        DOMExceptionCode::kNotFoundError,        "The Element argument should be a shadow-including inclusive "        "descendant of the target element.");    return;  }  // ...  validity_flags_ = flags;  validation_anchor_ = anchor;  SetCustomValidationMessage(message);  SetNeedsValidityCheck();}

In plain words, line by line:

  1. Lines 1 to 4 take the flags, the message, and the anchor.
  2. Line 6 asks two things: is any flag true, and is the message empty? When both are true, lines 7 to 9 throw the TypeError, before anything is kept.
  3. Lines 13 to 21 check the anchor. The next section explains them.
  4. Lines 23 to 25 keep the flags, the anchor, and the message. Line 26 tells the rest of Chrome to check the element again.

Read them back with internals.validity and internals.validationMessage, as the playground does. The HTML Standard starts every flag at false and the message empty.

Why it matters: one call states the whole truth about the value. Forget the {}, and an old problem stays. The form will never send.

What is the anchor argument of setValidity()?

When a form stops, the browser does two things. It points its message at something, and it moves focus somewhere. The validation anchor, the third argument, decides both. The HTML Standard tells browsers to use it, in place of the host, when they bring the problem to the person's attention.

Leave it out, and the anchor is the host. That can go wrong. Here is tea-cups with three parts: -, the number, and +. It's always 7, so it's always invalid. Press Order for each choice. Only lines 7 and 9 of the tab change:

Playground: where do the message and focus go?
An invalid tea-cups, and a page that prints where focus wentPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-cups name="cups"></tea-cups>  <button>Order</button></form><script src="tea-cups.js"></script><script>  const cups = document.querySelector("tea-cups");  cups.addEventListener("invalid", () => {    setTimeout(() => {      const inside = cups.shadowRoot.activeElement;      console.log("Focus:", inside ? inside.id : document.activeElement.textContent);    });  });  document.querySelector("#order").addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent");  });</script>
ResultLoading…
Try it yourself
Nothing to focus: no message at all

With no anchor, the anchor is the host. The host can't take focus, and it doesn't delegate focus. So Chrome shows no message, and focus stays on Order. The form still isn't sent. DevTools' Console says why.

The page stays the same. Only lines 7 and 9 of the tea-cups.js tab change.
  • In the tea-cups.js tab, line 7 attaches the shadow root, with or without delegatesFocus. Line 8 puts -, the number, and + in it.
  • Line 9 picks the anchor. undefined means none, the same as leaving it out. Line 10 passes it on.
  • On the page, line 8 waits for invalid. Line 9 lets the browser finish. Line 10 finds what has focus inside the shadow root, and line 11 prints its id, or the text of the element outside that has focus.
  • No anchor: Focus: Order, and no message at all.
  • No anchor, with delegatesFocus: Focus: less. The message points at the whole host.
  • Anchor the + button: Focus: more. The message points at +.
  • Anchor the number: Focus: less. The message points at the number.
Three columns, each the same invalid tea-cups with -, 7, and + after a failed Order. No anchor: focus stays on Order, and there is no message. Anchor the + button: focus goes to +, and the message Pick at most 6 cups. points at +. Anchor the number: focus goes to -, and the message points at 7.No anchorfocus stays on Order-7+no messageAnchor: the + buttonfocus-7+Pick at most 6 cups.Anchor: the numberfocus-7+Pick at most 6 cups.
The same failed Order, three anchors. The message points at the anchor. Focus goes to the anchor too, or, when it can't take focus, to the host's first button. With nothing to focus, there's no message at all.

Chrome follows one rule, in its ShowValidationMessage():

Where Chrome sends focus and the message, from listed_element.cc lines 656 to 666C++
void ListedElement::ShowValidationMessage() {  Element& element = ValidationAnchor();  element.scrollIntoViewIfNeeded(false);  if (element.IsFocusable()) {    element.Focus();  } else {    Element& host = GetHostOrFocusDelegate();    host.Focus();  }  UpdateVisibleValidationMessage();}

In plain words, line by line:

  1. Line 2 takes the anchor, or the host when there's none. Line 3 scrolls it into view.
  2. Lines 4 and 5 focus the anchor, if it can take focus.
  3. Lines 6 to 8 focus the host instead. GetHostOrFocusDelegate() gives the host's first control when the host delegates focus, as lesson 14.1 showed.
  4. Line 10 draws the message at the anchor.

And when nothing can take focus, as in the first choice? Then Chrome's ValidateInteractively() skips that control. It writes an error in DevTools' Console instead:

Chrome's error for an invalid control nothing can focusText
An invalid form control with name='cups' is not focusable.

The form still isn't sent. Asha sees nothing happen. If you ever meet this error, give the element an anchor that can take focus, or let the host delegate focus.

Real-life analogyThe sticky arrow on a bank form

At the bank, Asha fills in a long form. She misses one line. The clerk doesn't hand back the whole stack and say "something's wrong". She sticks a small arrow on the exact line: Sign here. Asha's pen goes straight to it.

In real life: The sticky arrow: Sign here
In JavaScript: The browser's message, at the anchor
In real life: Where Asha puts her pen
In JavaScript: Where focus goes
In real life: The line she missed
In JavaScript: The anchor, like the + button
In real life: Handing back the whole stack
In JavaScript: No anchor: the message points at the host

Which elements can be an anchor? The host itself, or anything inside it: in its shadow root, or a child of the host. Lines 13 to 21 of Chrome's setValidity() above check that. Anything else throws:

An anchor outside the element (an error on purpose)Pop out in the code editor (opens in a new tab)JavaScript
class TeaCups extends HTMLElement {
  static formAssociated = true;
}
customElements.define("tea-cups", TeaCups);
const internals = new TeaCups().attachInternals();
internals.setValidity({ rangeOverflow: true }, "Pick at most 6 cups.", document.body);

Line 6 passes document.body. Chrome throws a NotFoundError: "The Element argument should be a shadow-including inclusive descendant of the target element." Shadow-including means the host's shadow root counts. Inclusive means the host itself counts.

So which anchor should you pick? The part the person should fix. When the host wraps an input, as in lesson 16.1's container, that's the input. Caleb Williams, Burton Smith, and the WebKit blog all pass the inner input.

Why it matters: with nothing to focus, the form stops in silence. The anchor tells the person where to look.

What is the difference between checkValidity() and reportValidity()?

Both ask the same question: is the element valid? The difference is who hears the answer.

  • checkValidity() is quiet. If the element is invalid, it fires an invalid event at it and returns false. Nothing changes on screen.
  • reportValidity() does the same. Then it shows the message and moves focus, as the anchor says. The report validity steps skip that part if a listener cancels the event.

Both live on the internals, which your class keeps to itself. A page can call them on an input, though. So give your element methods that pass the call on, as this tea-cups does:

A form with Check, Report, Order, and Order anywayPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-cups name="cups"></tea-cups>  <button type="button" id="check">Check</button>  <button type="button" id="report">Report</button>  <button>Order</button>  <button formnovalidate>Order anyway</button></form><script src="tea-cups.js"></script><script>  const form = document.querySelector("#order");  const cups = document.querySelector("tea-cups");  cups.addEventListener("invalid", () => console.log("invalid event"));  form.querySelector("#check").addEventListener("click", () => {    console.log("checkValidity():", cups.checkValidity());  });  form.querySelector("#report").addEventListener("click", () => {    console.log("reportValidity():", cups.reportValidity());  });  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new FormData(form).get("cups"), "cups");  });</script>
ResultLoading…
tea-cups.js: always 7, with checkValidity() and reportValidity()JavaScript
class TeaCups extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  constructor() {
    super();
    this.attachShadow({ mode: "open", delegatesFocus: true }).innerHTML =
      '<button id="less">-</button> <output id="number">7</output> <button id="more">+</button>';
    this.#internals.setFormValue("7");
    this.#internals.setValidity({ rangeOverflow: true }, "Pick at most 6 cups.");
  }

  checkValidity() {
    return this.#internals.checkValidity();
  }

  reportValidity() {
    return this.#internals.reportValidity();
  }

  get willValidate() {
    return this.#internals.willValidate;
  }
}
customElements.define("tea-cups", TeaCups);
  • In the tab, line 10 makes the cups invalid from the start. Lines 13 to 19 pass checkValidity() and reportValidity() on to the internals. Lines 21 to 23 do the same for willValidate.
  • On the page, line 12 prints each invalid event. Lines 13 to 18 wire up Check and Report.
  • Line 5 is Order. Line 6 is Order anyway, with formnovalidate.

Press the four buttons in turn:

  • Check: invalid event, then checkValidity(): false. Focus stays where it was.
  • Report: invalid event, then reportValidity(): false. The message shows, and focus moves to -.
  • Order: invalid event, and nothing more. The form stopped.
  • Order anyway: Sent: 7 cups. The check was skipped.
Real-life analogyRavi checks an order ticket

Ravi reads an order ticket. Nine cups? That's more than the kitchen can make. He can make a note on his own pad and say nothing. Or he can walk to Asha's table, point at the line, and tell her. Either way, the ticket doesn't go to the kitchen yet.

In real life: A note on his own pad
In JavaScript: checkValidity(): an invalid event and false
In real life: Walking to the table and pointing
In JavaScript: reportValidity(): the message and focus
In real life: Sending the ticket to the kitchen
In JavaScript: Submitting the form
In real life: Meena saying: make it anyway
In JavaScript: formnovalidate

So what does Order do? The submit steps check the form first, unless the form has novalidate or the button has formnovalidate. The check walks the form's controls in page order and fires invalid at each invalid one. That event doesn't bubble. Then the browser reports the first one that can take focus. Only when nothing is invalid does submit fire. The table lists every way to check. Read each row across:

Every way to check a form control
Way to checkFires invalid?Shows the message and moves focus?Sends the form if valid?
checkValidity()Yes, at the element, when it's invalid.No.No. It only checks.
reportValidity()Yes, when it's invalid.Yes, unless a listener cancels the invalid event.No. It only checks.
A submit button, or requestSubmit()Yes, at every invalid control, in page order.Yes, for the first invalid control that can take focus.Yes.
novalidate on the form, or formnovalidate on the buttonNo.No.Yes, valid or not.
form.submit()No.No.Yes, valid or not.

Which controls does the form check?

Not every control is checked. A control the form checks is a candidate for constraint validation. willValidate says whether it is one. Try five ways to place the host. Only line 2 changes:

Playground: which controls does the form check?
The invalid tea-cups, placed five waysPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-cups name="cups"></tea-cups>  <button>Order</button></form><script src="tea-cups.js"></script><script>  const form = document.querySelector("#order");  const cups = document.querySelector("tea-cups");  console.log("willValidate:", cups.willValidate);  console.log("checkValidity():", cups.checkValidity());  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Cups sent:", new FormData(form).get("cups") ?? "none");  });</script>
ResultLoading…
Try it yourself
Checked, and invalid

The host is a candidate, so willValidate is true and the check fails. Order shows the message at the host and sends nothing.

Only line 2 changes. The tea-cups.js tab is the one above. Press Order after each choice.
  • Line 9 prints willValidate. Line 10 prints what checkValidity() returns.
  • Lines 11 to 14 print the cups the form sends, when Order gets that far.
  • No attribute: willValidate: true and checkValidity(): false. Order stops.
  • disabled, or inside <fieldset disabled>: false and true. Order prints Cups sent: none.
  • readonly: false and true. Order prints Cups sent: 7.
  • hidden: true and false. Order stops, and shows nothing.

Lesson 16.1's table said readonly takes the element out of the check. The HTML Standard says that's all it does for a form-associated element. Chrome's RecalcWillValidate() checks three things: a datalist parent, disabled, and readonly. hidden isn't one of them. A hidden invalid element stops the form, and nothing on screen says why.

Why it matters: use checkValidity() to decide, and reportValidity() to tell the person. And look for hidden controls when a form won't send.

Does :user-invalid work on custom elements?

An invalid form-associated element matches :invalid, like an input. Page CSS can style it from outside, as tea-cups:invalid. The class's own CSS can style it from inside, as :host(:invalid), the way lesson 11.2 used :host().

But :invalid matches as soon as the flags say so. That's before the person has done anything. An empty required box is red when the page opens. That's why :user-invalid exists. On an input, it waits until the person has changed the value or tried to send the form, as MDN describes.

Does it work on your element? Here is the name Meena writes on the cup. It's required. Try three rules for a red outline. Only line 2 changes:

Playground: when does the outline show?
A required name for the cup, with one CSS rulePop out in the code editor (opens in a new tab)HTML
<style>  tea-name:invalid { outline: 2px solid firebrick; }</style><form id="order">  <tea-name name="cup-name"></tea-name>  <button>Order</button></form><script src="tea-name.js"></script><script>  const form = document.querySelector("#order");  const cupName = document.querySelector("tea-name");  const show = (when) => console.log(when,    ":invalid", cupName.matches(":invalid"),    ":user-invalid", cupName.matches(":user-invalid"),    ":state(user-invalid)", cupName.matches(":state(user-invalid)"));  show("At first:");  cupName.addEventListener("invalid", () => setTimeout(() => show("After Order:")));  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new FormData(form).get("cup-name"));  });</script>
ResultLoading…
Try it yourself
Red before Asha has typed a thing

:invalid matches as soon as the flags say so. The box is empty and required, so the outline is there when the page opens.

Only line 2 changes. Press Order to see the outline after a failed Order.
tea-name.js: a required box with a user-invalid stateJavaScript
class TeaName extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();
  #touched = false;

  constructor() {
    super();
    this.attachShadow({ mode: "open", delegatesFocus: true }).innerHTML =
      '<input aria-label="Name for the cup">';
    const box = this.shadowRoot.querySelector("input");
    box.addEventListener("input", () => this.#check(box));
    box.addEventListener("change", () => {
      this.#touched = true;
      this.#check(box);
    });
    this.addEventListener("invalid", () => {
      this.#touched = true;
      this.#check(box);
    });
    this.#check(box);
  }

  #check(box) {
    this.#internals.setFormValue(box.value);
    if (box.value) this.#internals.setValidity({});
    else this.#internals.setValidity({ valueMissing: true }, "Write a name for the cup.", box);
    if (this.#touched && !this.#internals.validity.valid) this.#internals.states.add("user-invalid");
    else this.#internals.states.delete("user-invalid");
  }
}
customElements.define("tea-name", TeaName);
  • On the page, line 2 is the rule. Lines 12 to 15 print three matches. Line 16 prints them at first, and line 17 prints them again after a failed Order.
  • In the tab, line 4 starts a flag, #touched, at false. Line 11 checks the box on every keystroke.
  • Lines 12 to 15 set #touched when the box changes and loses focus. Lines 16 to 19 set it on an invalid event, after a failed Order.
  • Line 26 sets valueMissing while the box is empty, anchored at the box.
  • Lines 27 and 28 add the user-invalid custom state while it's touched and invalid. A custom state is a name your class turns on, which CSS reads with :state().

Every choice prints the same two lines:

  • At first: :invalid true :user-invalid false :state(user-invalid) false
  • After Order: :invalid true :user-invalid false :state(user-invalid) true

So in Chrome, :user-invalid never matches. The HTML Standard defines it for input, textarea, and select only. Those three keep a flag that says the person has interacted. A custom element has no such flag. Chrome's guide to form-associated elements warns that browsers don't agree here, so don't rely on it.

A table of cards. Rows: :invalid, :user-invalid, :state(user-invalid). Columns: at first, and after Order. :invalid shows a red outline in both. :user-invalid shows it in neither. :state(user-invalid) shows it only after Order.At firstAfter Order:invalidred outlinered outline:user-invalidred outlinered outline:state(user-invalid)red outlinered outline
The same empty box, styled three ways. :invalid is red before Asha has typed a thing. In Chrome, :user-invalid never matches a custom element. The custom state waits until she has tried.
Real-life analogyA teacher who marks blank answers

A teacher hands out a test. Before anyone writes a word, she walks round and marks every blank answer wrong. Nobody could have done better yet. A fair teacher waits until you hand the paper in, or at least finish a question.

In real life: Marking every blank answer before anyone writes
In JavaScript: :invalid when the page opens
In real life: Waiting until the paper is handed in
In JavaScript: Waiting for a failed Order, the invalid event
In real life: Waiting until you finish a question
In JavaScript: Waiting for change
In real life: Her own mark in the margin
In JavaScript: :state(user-invalid)

Web Awesome's form controls do the same. They set user-invalid and user-valid custom states, and count an invalid event as interaction. Inside the class's own CSS, the state reads :host(:state(user-invalid)). The kit uses that later.

Why it matters: red before anyone has typed tells people they did something wrong. Wait until they have tried.

How do you add required, min, and max to a custom element?

An input reads required, min, max, and step, and checks itself. On your element, those attributes mean nothing to the browser. You read them, and you set the flags. Here is loose tea by weight. Leaf and Kettle sells from 5 g to 500 g, in 5 g scoops:

A form with loose tea by weightPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-grams name="grams" required min="5" max="500" step="5"></tea-grams>  <button type="button" id="check">Check</button></form><script src="tea-grams.js"></script><script>  const grams = document.querySelector("tea-grams");  document.querySelector("#check").addEventListener("click", () => {    console.log(grams.validationMessage || "Valid");  });</script>
ResultLoading…
tea-grams.js: required, min, max, and step, checked by handJavaScript
class TeaGrams extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  constructor() {
    super();
    this.attachShadow({ mode: "open", delegatesFocus: true }).innerHTML =
      '<input inputmode="decimal" aria-label="Grams"> g';
    const box = this.shadowRoot.querySelector("input");
    box.addEventListener("input", () => this.#check(box));
    this.#check(box);
  }

  #check(box) {
    const text = box.value.trim();
    const grams = Number(text);
    const number = text !== "" && !Number.isNaN(grams);
    const [min, max, step] = ["min", "max", "step"].map((name) => Number(this.getAttribute(name)));
    const flags = {
      valueMissing: this.hasAttribute("required") && text === "",
      badInput: text !== "" && Number.isNaN(grams),
      rangeUnderflow: number && grams < min,
      rangeOverflow: number && grams > max,
      stepMismatch: number && (grams - min) % step !== 0,
    };
    const messages = {
      valueMissing: "Type how many grams.",
      badInput: "Type a number, like 50.",
      rangeUnderflow: `Order at least ${min} g.`,
      rangeOverflow: `Order at most ${max} g.`,
      stepMismatch: `Order in steps of ${step} g.`,
    };
    const first = Object.keys(flags).find((flag) => flags[flag]);
    this.#internals.setValidity(flags, first ? messages[first] : "", box);
    this.#internals.setFormValue(text);
  }

  get validationMessage() {
    return this.#internals.validationMessage;
  }
}
customElements.define("tea-grams", TeaGrams);
  • On the page, line 2 gives tea-grams four attributes. Lines 8 to 10 make Check print the message, or Valid.
  • In the tab, line 10 checks again on every keystroke. Line 11 checks once at the start, so an empty box is invalid from the first moment.
  • Lines 15 and 16 read the text and turn it into a number. Line 17 is true when there's text and it is a number. Line 18 reads the three number attributes.
  • Lines 19 to 25 build the flags, one rule each. Line 24 is the step rule: a whole number of 5 g steps from min, the way an input counts them.
  • Lines 26 to 32 hold a message for each flag.
  • Line 33 finds the first true flag. Line 34 sets every flag at once, with that flag's message, anchored at the box.

Type each amount and press Check:

  • Nothing: Type how many grams.
  • 4: Order at least 5 g.
  • 503: Order at most 500 g.
  • 52: Order in steps of 5 g.
  • fifty: Type a number, like 50.
  • 50: Valid.

These are an input's rules. The course set fifteen amounts, like -5, 52.5, and 1e2, on both tea-grams and <input type="number" required min="5" max="500" step="5">. Chrome raised the same flags on both, every time. Notice 503: it's over 500 and not in 5 g steps, so two flags are true. The person sees one message. Fix that one, and the next shows.

There's another way: borrow the rules. Make a number box that's never on the page. Copy your attributes onto it, and pass on its flags and its message. Material Web's checkbox validator does this with a checkbox:

tea-grams.js with borrowed rules (a fragment)JavaScript
  #check(box) {
    const native = Object.assign(document.createElement("input"), {
      type: "number",
      required: this.hasAttribute("required"),
      min: this.getAttribute("min"),
      max: this.getAttribute("max"),
      step: this.getAttribute("step"),
      value: box.value,
    });
    this.#internals.setValidity(native.validity, native.validationMessage, box);
    this.#internals.setFormValue(box.value);
  }
  • Lines 2 to 9 make the number box and copy the four attributes and the value onto it.
  • Line 10 passes its flags, its message, and the anchor. A ValidityState works as the flags object, as Burton Smith shows.

Then the messages are the browser's, in the person's language. For 503, Chrome says Value must be less than or equal to 500. For 52, it says Please enter a valid value. The two nearest valid values are 50 and 55. The cost: you can't word them yourself, and the number box decides what counts as a number. Web Awesome mixes the two. Its own rules set the flags, and it borrows only the browser's message for a required field.

Whichever way you choose, check on every change, the way lesson 16.2 hands over the value. A check in the form's submit listener comes too late: the form has checked every control before submit fires. Exercise 3 shows it.

Why it matters: the browser enforces only the rules you turn into flags.

How do screen readers hear a custom element's error?

The browser's message isn't part of the page. Each browser draws its own, and you can't style it, as MDN's aria-invalid page notes. So show the message in the page too, next to the box, and connect the two:

  • Put aria-invalid="true" on the element that gets focus, once you show the error. For an empty required field, MDN asks you to wait until the person has tried to send.
  • Point that element's aria-describedby at the message, in the same shadow root, as lesson 13.4 did for a hint.

Here is a gift code. Codes look like LK-4821:

A form with a gift codePop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-code name="code" pattern="LK-[0-9]{4}"></tea-code>  <button>Order</button></form><script src="tea-code.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new FormData(form).get("code") || "no code");  });</script>
ResultLoading…
tea-code.js: a pattern checked by hand, and an error people can findJavaScript
class TeaCode extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();
  #tried = false;

  constructor() {
    super();
    this.attachShadow({ mode: "open", delegatesFocus: true }).innerHTML = `
      <label for="box">Gift code</label>
      <input id="box" aria-describedby="error">
      <small id="error" hidden></small>`;
    const box = this.shadowRoot.querySelector("input");
    box.addEventListener("input", () => this.#check(box));
    this.addEventListener("invalid", () => {
      this.#tried = true;
      this.#show(box);
    });
    this.#check(box);
  }

  #check(box) {
    const pattern = new RegExp(`^(?:${this.getAttribute("pattern")})$`, "v");
    this.#internals.setFormValue(box.value);
    if (box.value === "" || pattern.test(box.value)) this.#internals.setValidity({});
    else this.#internals.setValidity({ patternMismatch: true }, "Use LK- and four digits, like LK-4821.", box);
    if (this.#tried) this.#show(box);
  }

  #show(box) {
    const invalid = !this.#internals.validity.valid;
    box.ariaInvalid = String(invalid);
    const error = this.shadowRoot.querySelector("#error");
    error.textContent = invalid ? this.#internals.validationMessage : "";
    error.hidden = !invalid;
  }
}
customElements.define("tea-code", TeaCode);
  • On the page, line 2 gives tea-code a pattern attribute.
  • In the tab, lines 9 to 11 are a label, the box, and an empty error. Line 10 points the box's aria-describedby at the error.
  • Line 13 checks on every keystroke. Lines 14 to 17 run after a failed Order: they note that Asha tried, and show the error.
  • Line 22 builds the pattern the way an input does: the whole value must match, with the v flag. Line 24 says an empty box or a match is valid. Line 25 sets patternMismatch, anchored at the box.
  • Line 26 updates the error once she has tried, so it goes away as soon as the code is right.
  • Lines 29 to 35 show the error. Line 31 sets aria-invalid on the box. Lines 33 and 34 fill in the text and show it.

Type LK-12 and press Order. Focus goes to the box, Chrome shows its message, and the error appears under the box. Here is the box's row in Chrome's accessibility tree, before and after:

The gift code's row in Chrome's treeText
At first:          textbox "Gift code"
After a failed Order: textbox "Gift code", invalid, description: "Use LK- and four digits, like LK-4821."

After the failed Order, the box is invalid and described by the error. Both sit on the element that has focus, so a screen reader hears them together. Now type LK-4821. The error goes away, and Order prints Sent: LK-4821. The course also checked nine codes against an input with the same pattern, and Chrome agreed on every one.

Why only after Order, and not when the box loses focus? The course tried that. The error then appears just as Asha presses Order. The button moves between her press and her release, and the click is lost.

Real-life analogyA wet floor sign

When the café floor is wet, Meena puts a yellow sign right on the wet spot. Anyone walking there sees it. A sign left in the cupboard warns nobody. A sign by the front door says something is wet, but not where.

In real life: The sign on the wet spot
In JavaScript: The error, tied to the box with aria-describedby
In real life: Someone walking to that spot
In JavaScript: Focus landing on the box
In real life: The sign left in the cupboard
In JavaScript: A message nothing points to
In real life: A sign by the front door
In JavaScript: A message somewhere else on the page

When the host itself is the control, with a role from internals.role as in lesson 13.2, set the state on the internals instead:

The error state on the internals (a fragment)JavaScript
// In a class whose host is the control, with this.#internals.role = "textbox":
this.#internals.ariaInvalid = shown ? "true" : "false";

Chrome marks an invalid form-associated host as invalid in its tree on its own, from the moment the flags say so. That's the too-early problem again. Setting ariaInvalid to "false" until you show the error keeps the tree in step with the screen. No live region is needed here: focus lands on the control, and its description carries the message.

Why it matters: an error only helps when people can find it. Put it where focus lands.

Adding validation to the kit's order form

The kit's new version, kitAfter163, gives both form controls a rule. tea-quantity takes min and max. tea-blend takes required. Here is the order form with both:

The order form with a required blend and at most 6 cupsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order">  <tea-blend name="tea" label="Blend" required><option>Sencha</option><option>Jasmine</option><option>Oolong</option></tea-blend>  <label for="cups">Cups</label>  <tea-quantity id="cups" name="cups" max="6"></tea-quantity>  <button type="button" id="again">Same as last time</button>  <button>Order</button></form><script type="module">  import "./tea-kit/index.js";  const form = document.querySelector("#order");  document.querySelector("#again").addEventListener("click", () => {    form.elements.cups.value = 8;  });  form.addEventListener("submit", (event) => {    event.preventDefault();    for (const [name, value] of new FormData(form)) console.log(name, value);  });</script>
ResultLoading…
  • Line 3 is the blend, now required. Line 5 is the quantity, with max="6".
  • Lines 12 to 14: Same as last time sets 8 cups, Asha's last order.
  • Lines 15 to 18 print the entries when the form is sent.
  1. Press Same as last time, then Order. Nothing prints. Both controls are invalid. Focus goes to Sencha, the blend's first checkbox, where Chrome shows its message. Each control also shows its own error: Pick at least one tea. and Pick 6 or fewer.
  2. Tick Sencha and press Order again. Now focus goes to the quantity's - button, and the message points at the number.
  3. Press - twice, then Order. It prints tea Sencha and cups 6.
Asha presses Order with no tea ticked and 8 cups. The form checks its controls in page order. The blend is invalid and gets an invalid event, then focus and the message Pick at least one tea. The quantity is invalid too and gets an invalid event. The submit event never fires.In page orderblend: no teacups: 8invalid eventinvalid eventfocus, messagethe first thatcan take focussubmit eventnever fires
Pressing Order checks every control first, in page order. Each invalid one gets an invalid event. Only the first one that can take focus shows the browser's message, and the form isn't sent.

Here are the lines of tea-quantity.js that check the number:

How tea-quantity.js checks its numberJavaScript
  static observedAttributes = ["hint", "min", "max"];
// ...
  #validate() {
    const min = toInteger(this.getAttribute("min"), null);
    const max = toInteger(this.getAttribute("max"), null);
    const number = this.shadowRoot.getElementById("number");
    if (min !== null && this.#value < min) {
      this.#internals.setValidity({ rangeUnderflow: true }, `Pick ${min} or more.`, number);
    } else if (max !== null && this.#value > max) {
      this.#internals.setValidity({ rangeOverflow: true }, `Pick ${max} or fewer.`, number);
    } else {
      this.#internals.setValidity({});
    }
    this.#showError();
  }

  #showError() {
    const shown = this.#touched && !this.#internals.validity.valid;
    const error = this.shadowRoot.getElementById("error");
    error.textContent = shown ? this.#internals.validationMessage : "";
    error.hidden = !shown;
    if (shown) this.#internals.states.add("user-invalid");
    else this.#internals.states.delete("user-invalid");
  }
  • Line 1: it watches min and max, so a new limit is checked at once.
  • Lines 4 and 5 read them as whole numbers, with lesson 5.2's toInteger(). A missing or broken value gives null: no limit.
  • Lines 7 to 10 set rangeUnderflow or rangeOverflow, anchored at the number. The number can't take focus, so the host does, and passes focus to -.
  • Line 12 clears the flags. Line 14 updates the error.
  • Lines 17 to 24 show the error only once Asha has pressed a button or tried to send. Lines 22 and 23 turn the user-invalid state on and off.

#validate() runs on every click, in lesson 16.2's value setter, and when min or max changes. The blend's runs on every tick, and when name or required changes. Its anchor is the first checkbox. Both controls show the error in an error part, and describe what you can focus with it. Here are the quantity's rows in Chrome's tree after step 2:

The quantity's rows in Chrome's tree after step 2Text
button "One cup less", focused, description: "Pick 6 or fewer."
status "Cups", description: "Pick 6 or fewer."
button "One cup more", description: "Pick 6 or fewer."

Both also gain validity, validationMessage, willValidate, checkValidity(), and reportValidity(), like an input. Without min, max, or required, they stay valid. The course's test runs pages from earlier lessons with both versions of the kit, and every printed line, box, and tree stays the same. The JSDoc and custom-elements.json document the new attributes, members, the error part, the --tea-color-error property, and the user-invalid state. tokens.css sets that property to firebrick, at 6.67:1 on paper, measured the way lesson 15.1 measured the others.

Now sort some forms by whether they get checked:

Does the form check it before sending?
  • An invalid tea-cups, and Asha presses Order.
  • An invalid tea-cups with no name, and Asha presses Order.
  • An invalid tea-cups with the hidden attribute.
  • An invalid tea-cups, and the page calls form.requestSubmit().
  • An invalid tea-cups with disabled.
  • An invalid tea-cups with readonly.
  • An invalid tea-cups inside <fieldset disabled>.
  • An invalid tea-cups in a form with novalidate.
  • An invalid tea-cups, and Asha presses a button with formnovalidate.
Try it yourself
0 of 9 correct

Each form holds an invalid tea-cups. Sort each one: does the form check it and stop, or send anyway?

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Why it matters: the kit's form now stops a bad order and says why, right where Asha can fix it.

Common mix-ups

  • "A flag without a message is fine." No. A true flag with no message throws a TypeError, and nothing changes.
  • "setValidity() adds to the flags I set before." No. Each call replaces all ten. Pass {} to clear them.
  • "The anchor can be any element." No. It must be the host or inside it. Anything else throws a NotFoundError.
  • "Without an anchor, the browser finds the right part." No. The anchor is the host. If nothing there can take focus, the form stops with no message.
  • "checkValidity() shows the message." No. It fires invalid and returns false. Only reportValidity() and a submit show it.
  • "The form checks disabled and readonly controls too." No. Both are barred, so willValidate is false and the form sends anyway.
  • "hidden takes an element out of the check." No. A hidden invalid element still stops the form, with no message.
  • ":user-invalid works on my element." No. The standard defines it only for input, textarea, and select, and Chrome never matches it on a custom element. Use a custom state.
  • "Checking in the submit listener is enough." No. The form checks before submit fires. Check on every change.
  • "rangeOverflow makes the host match :out-of-range." No. That needs an input's own min and max. Chrome says false.
  • "Checks in the page keep bad data off the server." No. The HTML Standard says servers shouldn't rely on them. Check again on the server.

Practice exercises

Exercise 1 · Warm-upA flag with no message

Predict what the page prints, then run it.

<tea-cups></tea-cups><script>  customElements.define("tea-cups", class extends HTMLElement {    static formAssociated = true;    internals = this.attachInternals();  });  const cups = document.querySelector("tea-cups");  try {    cups.internals.setValidity({ valueMissing: true });    console.log("Set");  } catch (error) {    console.log(error.name);  }</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA readonly host

    tea-cups has readonly and a rangeOverflow flag. Predict what checkValidity() prints, then run it.

    <form id="order">  <tea-cups name="cups" readonly></tea-cups></form><script>  customElements.define("tea-cups", class extends HTMLElement {    static formAssociated = true;    internals = this.attachInternals();  });  const cups = document.querySelector("tea-cups");  cups.internals.setValidity({ rangeOverflow: true }, "Pick at most 6 cups.");  console.log(cups.internals.checkValidity());</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeChecked too late

      Press + once, so the cups are 7, and press Order. It prints Sent: 7 cups. Fix the tea-cups.js tab so 7 cups are never sent. What does Order print then?

      <form id="order">  <tea-cups name="cups"></tea-cups>  <button>Order</button></form><script src="tea-cups.js"></script><script>  const form = document.querySelector("#order");  form.querySelector("tea-cups").addEventListener("invalid", () => {    console.log("Not sent: the form found a problem.");  });  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new FormData(form).get("cups"), "cups");  });</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeNothing to focus

        The kitchen needs a note. Press Order with the note empty: focus stays on Order, and no message shows. DevTools says the control is not focusable. Fix the tea-note.js tab. Where is focus after Order then?

        <form id="order">  <tea-note name="note"></tea-note>  <button>Order</button></form><script src="tea-note.js"></script><script>  const note = document.querySelector("tea-note");  note.addEventListener("invalid", () => {    setTimeout(() => {      const inside = note.shadowRoot.activeElement;      console.log("Focus:", inside ? inside.id : document.activeElement.textContent);    });  });  document.querySelector("#order").addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent");  });</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeA gift code pattern

          Gift codes are LK- and four digits. Make tea-code invalid for anything else, with the message Use LK- and four digits. An empty box stays valid. Type LK-12 and press Check. What does it print?

          <form id="order">  <tea-code name="code"></tea-code>  <button type="button" id="check">Check</button></form><script src="tea-code.js"></script><script>  const code = document.querySelector("tea-code");  document.querySelector("#check").addEventListener("click", () => {    console.log(code.validationMessage || "Valid");  });</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeRed only after Order

            The page wants a red outline only after Asha has tried. Give tea-name a user-invalid custom state, like the one earlier in this lesson. Press Order with the box empty. What does the page print after Order?

            <style>  tea-name:state(user-invalid) { outline: 2px solid firebrick; }</style><form id="order">  <tea-name name="cup-name"></tea-name>  <button>Order</button></form><script src="tea-name.js"></script><script>  const cupName = document.querySelector("tea-name");  console.log("At first:", cupName.matches(":state(user-invalid)"));  cupName.addEventListener("invalid", () => {    setTimeout(() => console.log("After Order:", cupName.matches(":state(user-invalid)")));  });</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The validation quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does setValidity({ rangeOverflow: true }) do when you pass no message?

                Choose an answer to see the explanation.

              2. Question 2 of 7This page passes a message with no true flag. What does it print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <tea-cups></tea-cups>
                <script>
                  customElements.define("tea-cups", class extends HTMLElement {
                    static formAssociated = true;
                    internals = this.attachInternals();
                  });
                  const { internals } = document.querySelector("tea-cups");
                  internals.setValidity({ rangeOverflow: true }, "Pick at most 6 cups.");
                  internals.setValidity({}, "Pick at most 6 cups.");
                  console.log(JSON.stringify(internals.validationMessage));
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 7A failed Order. tea-cups set its anchor to the + button in its shadow root. Where does focus go?

                Choose an answer to see the explanation.

              4. Question 4 of 7Which call shows the browser's message to the person?

                Choose an answer to see the explanation.

              5. Question 5 of 7After a failed Order, does a form-associated custom element match :user-invalid in Chrome?

                Choose an answer to see the explanation.

              6. Question 6 of 7tea-cups has readonly and a rangeOverflow flag. Asha presses Order. What happens?

                Choose an answer to see the explanation.

              7. Question 7 of 7An invalid tea-cups has the hidden attribute. Asha presses Order. What happens?

                Choose an answer to see the explanation.

              Key takeaways

              • setValidity(flags, message, anchor) tells the form what's wrong. Each call replaces all ten flags, and {} clears them.
              • A true flag needs a message. A message counts only while a flag is true.
              • The anchor is where the message points and where focus goes. It's the host or inside it. If it can't take focus, the host or its focus delegate gets focus.
              • When nothing can take focus, the form stops with no message, and DevTools says the control is not focusable.
              • checkValidity() is quiet. reportValidity() shows the message. A submit checks every control in page order, unless novalidate or formnovalidate says not to.
              • disabled, readonly, and a disabled fieldset take an element out of the check. hidden doesn't.
              • :invalid matches from the start. The standard defines :user-invalid only for input, textarea, and select, so use a custom state that waits for the person.
              • Check required, min, max, and pattern yourself on every change, or borrow a hidden input's rules.
              • Show the error in the page, on the element that gets focus, with aria-invalid and aria-describedby.

              Remember the one-liner.
              Check your value on every change, tell the form with setValidity(), and give it an anchor that can take focus.

              Sources

              The facts on this page come from these standards, docs, source files, and posts:

              Support data comes from MDN's browser-compat-data. web.dev's guide has one more example of setValidity(), with customError.

              Coming next: Form lifecycle callbacks. It handles form reset, disabled fieldsets, and the back button's restore.

              CompleteFrontend Clear concepts. Working examples.