← Back to HTML & CSS, page 6

html-css-0116 · Hard senior

How can a custom element take part in a form like a native input?

Set static formAssociated = true and call attachInternals(). Then setFormValue sets what the form sends, and setValidity marks the control valid or invalid. The control still needs keyboard support and a role, so use native elements when they fit.

Full answer

A custom element is not a form control by default. A value inside its shadow tree is not sent when the form is submitted, and the form's validation ignores it. Two things change this.

  1. Set static formAssociated = true on the class. The browser then connects the element to its nearest form (or the one named in its form attribute).
  2. Call this.attachInternals(). The returned ElementInternals object lets the element tell the form what to send and whether it is valid.

Main methods:

  • internals.setFormValue(value) sets the value that the form sends under the element's name. It can be a string, a File or a FormData.
  • internals.setValidity({ valueMissing: true }, "Pick a value", anchorElement) marks the control invalid with a message. setValidity({}) makes it valid again.
  • The internals object also gives form, labels, validity, validationMessage, checkValidity() and reportValidity(). The form itself checks the control when it validates.
  • Optional callbacks: formResetCallback, formDisabledCallback and formAssociatedCallback, so the control can reset or disable itself with the form.

The element still needs real keyboard support and an accessible role. internals.role and internals.ariaChecked-style properties can set default semantics without adding attributes to the host. Where a native element fits, use it. Build a custom control only when a native one cannot do the job.

With no rating, the form is invalid and the message is "Choose a rating", and the form holds rating=0. After set(4), the form data holds rating=4 and the form is valid.

Test with real keyboard input and a screen reader before using such a control in production.

html
<form id="f">
  <star-rating id="r" name="rating"></star-rating>
</form>
<script>
  class StarRating extends HTMLElement {
    static formAssociated = true;
    constructor() { super(); this.internals = this.attachInternals(); this.set(0); }
    set(n) {
      this.value = n;
      this.internals.setFormValue(String(n));
      if (n === 0) this.internals.setValidity({ valueMissing: true }, "Choose a rating");
      else this.internals.setValidity({});
    }
  }
  customElements.define("star-rating", StarRating);
</script>

Checked in Chrome 156 only, by reading the form data and the validity state through ElementInternals. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • static formAssociated = true connects the element to a form.
  • attachInternals returns ElementInternals.
  • setFormValue sets the submitted value.
  • setValidity joins form validation.
  • Keyboard support and roles are still your job.

Common mistakes

  • Using a custom element for a form control when a native element would work.
  • Forgetting static formAssociated = true, so attachInternals gives no form behaviour.
  • Setting a form value but not building keyboard support and an accessible role.

Follow-ups

  • What does setFormValue do?
  • When is a native control better than a custom one?

Tips

  • Name the two steps: formAssociated and attachInternals.
  • Mention setFormValue and setValidity as the main methods.