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

