ElementInternals Form-Associated Custom Element

Let a custom element join form validation by attaching ElementInternals: set the submitted value and drive checkValidity with setValidity.

TypescriptForm Validation

Code

typescriptsnippet
36 lines
if (typeof document === "undefined") {
  console.log("rating-stars needs a browser DOM to register the custom element");
} else {
  // Form-associated custom element: the element participates in form
  // submission and constraint validation through ElementInternals
  class RatingStars extends HTMLElement {
    static formAssociated = true;

    readonly internals: ElementInternals;

    constructor() {
      super();
      this.internals = this.attachInternals();
    }

    setRating(value: number): void {
      this.internals.setFormValue(value === 0 ? null : String(value));
      if (value === 0) {
        this.internals.setValidity({ valueMissing: true }, "Pick at least one star");
      } else {
        this.internals.setValidity({});
      }
    }
  }

  customElements.define("rating-stars", RatingStars);

  const rating = document.createElement("rating-stars") as RatingStars;
  document.body.append(rating);

  rating.setRating(0);
  console.log("valid:", rating.internals.checkValidity(), "| message:", rating.internals.validationMessage);

  rating.setRating(4);
  console.log("valid:", rating.internals.checkValidity(), "| message:", JSON.stringify(rating.internals.validationMessage));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

rating-stars needs a browser DOM to register the custom element

Walking through the code

The snippet is organized around the class RatingStars.

What to watch for

  • Self-contained: imports go no further than what the runtime provides.
  • A browser is the runtime here: document are not available in Node.

Using it

The demo output is labeled (valid:), so the output lines each link back to the operation behind them.

Key statements

this.internals.setValidity({ valueMissing: true }, "Pick at least one star");
const rating = document.createElement("rating-stars") as RatingStars;
this.internals.setFormValue(value === 0 ? null : String(value));

Interactive Tools for This Topic

FAQ

Does ElementInternals Form-Associated Custom Element run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.