Search code examples
javascripthtmldompolymerweb-component

How to make an HTML form validate a custom HtmlInputElement?


I'd like to create a custom input element with a custom template and have the native HTML <form> respect it as it does the other native input elements. For example, when the element is invalid and the user tries to submit the form, the browser would trigger the validation logic on my custom element and prevent submission and show errors. Also, when the form is submitted or serialised, the value of the custom element is included also.

I've gotten as far as using the "is" attribute and a custom class that extends HtmlInputElement object, but I can't seem to use a custom template using this method.

How can I go about doing this if it's possible?

Examples using plain JavaScript as well as Polymer are welcomed.


Solution

  • One limitation to understand: in the current v1 version of custom elements being implemented across browsers (rather than the legacy v0 version which is definitely not going to be implemented across browsers going forward), a custom-element class can only extend HTMLElement .

    So feeding customElements.define a class that extends HtmlInputElement will fail.

    (All that said, unless as noted in a comment above, you use a polyfill.)

    But for a better answer to the specific question about making something that extends input, see the answer at Custom input element in native form.