Search code examples
htmlweb-componentnative-web-componentconstraint-validation-api

custom web component form element for constraint validation


Only some HTMLElements support the constraint validation api (e.g., HTMLButtonElement). I want to create a custom web component, which also supports the constraint validation api.

In the following an example is given for the desired outcome:

<form>
  <input name="title" required>
  <custom-form-component></custom-form-component>
</form>
<script>
  const form = document.querySelector('form');
  form.checkValidity();
</script>

The custom-form-component could call setCustomValidity on itself (based on the respective user input context) and validate itself true or false. Thus, the call on the form.checkValidity() should return true or false with respect to the outcome of the custom-form-component.

As I found from documentaion (e.g. on MDN) only for some element it is possible to attach a shadow root. It is not possible for form elements. However, only form elements suport the constraint validation api.

concrete question: How can I realise a custom web component, which supports constraint validation api?


Solution

  • This is a new introduction to Web Components. As of Sept 25, 2019 only Chrome 76 supports it.

    Here is an article provided by Google Web Devs:

    https://web.dev/more-capable-form-controls/

    It talks about the various additions to Web Components that let them properly integrate as a form element.

    This includes:

    1. Form validation
    2. The :disabled, :invalid and :valid CSS pseudoclasses
    3. The formdata event
    4. And a static formAssociated property that tells the browser to treat your element like a form control.

    Plus several other things that allows your control to function correction in a <form>