只有一些 HTMLElements 支持约束验证 api(例如,HTMLButtonElement)。我想创建一个自定义的 web 组件,它也支持约束验证 api。
下面给出了所需结果的示例:
<form>
<input name="title" required>
<custom-form-component></custom-form-component>
</form>
<script>
const form = document.querySelector('form');
form.checkValidity();
</script>
Run Code Online (Sandbox Code Playgroud)
的custom-form-component可以调用setCustomValidity其自身上(基于相应用户输入上下文)和验证本身真或假。因此,form.checkValidity()对于 的结果,对 的调用应该返回真或假custom-form-component。
正如我从文档中发现的(例如在 MDN 上),仅对于某些元素,可以附加影子根。表单元素是不可能的。但是,只有表单元素支持约束验证 api。
具体问题:如何实现支持约束验证api的自定义Web组件?
web-component shadow-dom native-web-component constraint-validation