liveBook · Manning

Form-associated custom element

As explained in Vanilla Web

A form-associated custom element is a custom HTML element that participates in a form's association, disabled-state, reset, and state-restoration behavior.

A custom field that only looks like an input may still be absent from form submission and validation. A form-associated custom element uses ElementInternals to participate in those behaviors. It can also appear in form.elements, associate with a label, and respond to form resets and disabled-state changes. section 9.1.1

Build the form contract explicitly:

  • Extend HTMLElement, declare static formAssociated = true, and call attachInternals() in the constructor. section 9.1.1
  • When the field value changes, update the internal control and call internals.setFormValue(value). Give the element a name so its value can be read from FormData. section 9.1.1
  • Use internals.setValidity(flags, message, anchor) for constraints such as a missing required value. Clear the flags when the value becomes valid; checkValidity() checks and can dispatch invalid, while reportValidity() also requests browser validation UI. section 9.1.1 section 9.1.2
Listing 9.1 A form-associated custom element
class FancyInput extends HTMLElement {
  static formAssociated = true;
  static observedAttributes = ["value", "required", "disabled"];

  #value = "";
  #input;

  constructor() {
    super();
    this.internals = this.attachInternals();
    this.attachShadow({ mode: "open" });

    this.shadowRoot.innerHTML = template;

    this.#input = this.shadowRoot.querySelector("input");
    this.#input.addEventListener("input", () => {
      this.value = this.#input.value;
    });
  }

  get value() {
    return this.#value;
  }

  set value(v) {
    this.#value = String(v ?? "");
    this.#input.value = this.#value;
    this.internals.setFormValue(this.#value);
    this.validate();
  }
}

customElements.define("fancy-input", FancyInput);

The field’s value setter keeps its shadow input, submitted value, and validation in sync. section 9.1.1

Form-specific callbacks keep the component aligned with its owner: formAssociatedCallback(form) observes association or its loss; formDisabledCallback(disabled) handles disabled changes, including those from an ancestor fieldset; formResetCallback() restores the default value; and formStateRestoreCallback(state, mode) handles restored state or form-fill data. These hooks matter particularly when internal state is richer than one string. section 9.2.3

Check submission, not just appearance

Place a named custom field inside a form, set its value to "test-value", and construct new FormData(form). Verify that formData.get(fieldName) returns "test-value". Test invalid values separately with checkValidity() or reportValidity(), including the validity state or message. section 9.7.3

Form association does not make a button inside Shadow DOM submit an outer form by itself. For a form-associated submit component, internals.form identifies the owning form; calling requestSubmit() on it runs validation and fires a submit event. section 15.6

How Vanilla Web covers it

How deep it goes
Works through setup, value synchronization, validation methods, lifecycle callbacks, and submission tests.
Examples
Uses a required custom text field, a FormData submission test, and a checkout form with custom fields and a submit button.
What it assumes
Assumes familiarity with HTMLElement-based custom elements and forms while showing how to enable form association.
What you can do after
Build it from scratch with ElementInternals, then test submitted values and validation behavior.
How it connects
Connects ElementInternals and Shadow DOM with FormData, constraint validation, and form lifecycle callbacks.

Also explained in

Compare how 2 books explain form-associated custom element →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.