Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 722
Stefan Avatar asked Oct 27 '25 12:10

Stefan


1 Answers

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>

like image 146
Intervalia Avatar answered Oct 30 '25 02:10

Intervalia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!