A plain custom element is invisible to forms: a <form> collects only its form-associated elements. A custom element becomes one with two steps:
static formAssociated = trueon the class.this.attachInternals(), which returns anElementInternalsobject, the element's private connection to the browser. Keep it private; it can be attached only once.
The browser then treats the element like a built-in control:
- Form owner: the ancestor
<form>, or the one named by itsformattribute; read it withinternals.form. It's listed inform.elements. name,disabled,readonlyattributes work: a disabled element (or one in a disabled<fieldset>) matches:disabledand isn't submitted;readonlybars it from validation.- Labels:
<label for="id">is associated (internals.labels), and clicking it focuses the element if it's focusable.
What the browser can't infer, you provide through internals:
- Value:
setFormValue(value, state).valueis a string, aFile, aFormData(several entries, names ignoringname) ornull(not submitted).stateis what the browser should hand back when it restores the form. - Validity:
setValidity({ valueMissing: true }, 'Pick a rating', anchor)makes the element:invalid, makesform.checkValidity()false, firesinvalidand blocks submission, with the message shown atanchor.setValidity({})clears it. - Callbacks:
formAssociatedCallback(form)when the owner changes,formResetCallback()onform.reset(),formDisabledCallback(disabled), andformStateRestoreCallback(state, mode)withmode"restore"or"autocomplete".
internals is private, so expose the usual control API yourself: value, form, validity, checkValidity(). ElementInternals also sets default ARIA semantics (internals.role); accessibility is a separate topic. attachInternals() throws NotSupportedError on a second call, on customized built-ins and on non-custom elements. MDN's data lists the form APIs in Chrome 77, Firefox 98 and Safari 16.4.