Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Forms and Accessibility

Form-Associated Custom Elements with Lit

Build custom form controls in Lit that submit with the form, validate and reset. Learn formAssociated, ElementInternals, setFormValue, setValidity and form lifecycle callbacks.

A native <input> takes part in a form automatically: its value is submitted, it participates in validation, form.reset() clears it, and fieldset[disabled] disables it. A custom element such as <star-rating> does none of that by default. The browser has no idea that it holds a value.

Form-associated custom elements (FACE) fix this. By opting in and using the ElementInternals API, a Lit component becomes a first-class form control. This lesson builds one step by step.

What you get from FACE

A real form control

Submits Appears in FormData
Validates Works with :invalid and checkValidity()
1 / 2

Before FACE, authors put a hidden <input> in the light DOM and kept it in sync. Now the element itself carries the value.

Opting in

Two steps: set static formAssociated = true, and call this.attachInternals() once, usually in the constructor. The returned ElementInternals object is your channel to the form.

A rating control that submits

setFormValue(value) tells the form what to submit under the element's name. The value can be a string, a File, or a FormData (to submit several entries). Passing null submits nothing. Calling it in willUpdate keeps the form value in step with every property change, including the initial one.

The preview form never posts to a server: the submit handler prints the data instead, as the examples on this site always do.

Validation with setValidity

ElementInternals plugs into the browser's constraint validation. Call setValidity(flags, message, anchor) with a flag such as valueMissing, and the control becomes :invalid, makes form.checkValidity() return false, and blocks submission, exactly like a native required input.

Required validation

After setValidity, the element exposes validity, validationMessage, willValidate, checkValidity() and reportValidity() (Lit does not add these; the browser does because the element is form-associated). The CSS pseudo-classes :invalid and :valid also work on the host.

Pass an empty object {} to setValidity to clear the error. The third argument, the anchor, is the element inside the shadow DOM the browser should point its error bubble at.

Form lifecycle callbacks

FACE adds four callbacks to your class. Implement the ones you need.

Callback Called when
formAssociatedCallback(form) the element is associated or disassociated with a form
formDisabledCallback(disabled) an ancestor fieldset[disabled] or the disabled attribute changes the disabled state
formResetCallback() the form is reset
formStateRestoreCallback(state, mode) the browser restores state (back navigation, autofill)
Reset and disabled

A disabled form control is left out of FormData, and the browser does that for you once the element is disabled through its form or fieldset.

Restoring and autofill: formStateRestoreCallback

When the user navigates back or the browser restores a session, it hands the saved value back through formStateRestoreCallback(state, mode). mode is "restore" or "autocomplete". Pass a second argument to setFormValue(value, state) to store richer state than the submitted string.

JavaScript
formStateRestoreCallback(state, mode) {
  this.value = Number(state);       // state is what we stored earlier
}

Reflecting the value for CSS and :state

Two helpful extras:

  • ElementInternals.states (a CustomStateSet) lets you expose custom pseudo-classes such as :state(checked). It is supported in current evergreen browsers; verify support for your audience.
  • ARIA through internals: this._internals.role = "slider" and this._internals.ariaValueNow = "3" give the host default semantics without adding attributes. The accessibility lesson uses this.
JavaScript
this._internals.states.add("checked");     // matches my-switch:state(checked)
this._internals.states.delete("checked");

Fallbacks and good habits

  • Always test inside a real <form>. FACE only matters when a form owns the element.
  • Keep the name and value API like a native input, including required, disabled, form and validity, so authors can predict it.
  • Do not forget the label. A form-associated element needs an accessible name; see the next lesson.
  • Browser support is broad in current evergreen browsers. For legacy browsers, a hidden <input> fallback is the usual approach.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which two steps make a custom element form-associated?

    Opt in with static formAssociated and call attachInternals() to get the ElementInternals object.
  2. 2. How does a form-associated element supply the value that is submitted?

    The form only submits what the element passes to setFormValue, under the element's name.
  3. 3. What does internals.setValidity({ valueMissing: true }, 'Please choose.', anchor) do?

    It sets a validation flag and message, making the control behave like an invalid native input.
  4. 4. Which callback runs when the user calls form.reset()?

    formResetCallback lets the control restore its default value.

Summary

  • Set static formAssociated = true and call attachInternals() to make a Lit component a real form control.
  • setFormValue supplies the submitted value; setValidity provides constraint validation.
  • Implement formResetCallback, formDisabledCallback and formStateRestoreCallback for complete behavior.
  • Treat the element like a native input: name, value, required, disabled, a label.

Next: Accessibility Basics for Components