简体   繁体   English

如何使 HTML 表单验证自定义 HtmlInputElement?

[英]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.我想使用自定义模板创建自定义输入元素,并让本机 HTML <form>像对待其他本机输入元素一样尊重它。 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.我已经使用“is”属性和扩展HtmlInputElement对象的自定义类,但我似乎无法使用使用此方法的自定义模板。

How can I go about doing this if it's possible?如果可能,我该怎么做?

Examples using plain JavaScript as well as Polymer are welcomed.欢迎使用纯 JavaScript 和 Polymer 的示例。

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 .要理解的一个限制:在当前跨浏览器实现的自定义元素的 v1 版本中(而不是遗留的 v0 版本,它肯定不会在未来的浏览器中实现),自定义元素类只能扩展HTMLElement

So feeding customElements.define a class that extends HtmlInputElement will fail.因此,为customElements.define一个扩展HtmlInputElement的类将失败。

(All that said, unless as noted in a comment above, you use a polyfill.) (总而言之,除非如上面的评论中所述,否则您将使用 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 .但要更好地回答有关制作扩展input的特定问题的答案,请参阅本机形式的自定义输入元素中的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM