你能用JavaScript触发自定义HTML5表单错误吗? [英] Can you trigger custom HTML5 form errors with JavaScript?
问题描述
如果我有像< input type =text>
这样的输入,我想在输入上触发原生错误,你可以这样做吗?喜欢(虚假代码) ele.triggerError('错误信息');
If i have an input like <input type="text">
and i want to trigger a native error on the input, can you do that? Like (faux code) ele.triggerError('Error Message');
它看起来像是:
错误http://tylergaw.com/storage/post_image_htmlFormErrors_defaultChrome.jpg
但是有自定义消息并且有自己的验证功能。例如,需要AJAX验证。
But with a custom message and for it's own validation function. Needed for AJAX validations for example.
推荐答案
触发本机错误的唯一方法是提交表单。虽然您可以使用 setCustomValidity
(如我在这里的回答中描述的那样)你可以用无效的事件href =http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#dom-cva-checkvalidatity =noreferrer> checkValidity
,这只为您提供了创建自己的验证UI的钩子。 这是一个简单的示例,您可以使用它来验证。
The only way to trigger the native error is to submit the form. Although you can set a custom message with setCustomValidity
(as described in my answer here) and you can trigger the invalid
event with checkValidity
, this only provides hooks for you to create your own validation UI. Here's a simple example you can play around with to verify.
请注意,如果您使用 submit()
方法提交表单,该方法将绕过验证API。但是,如果您触发提交<的点击
事件按钮可以在Firefox和Opera中使用,但不适用于Chrome。我现在就避免这样做。
Note that if you submit the form with the submit()
method that will bypass the validation API. But if you trigger the click
event of the submit button that will work in Firefox and Opera, but not Chrome. I'd avoid doing it right now.
这篇关于你能用JavaScript触发自定义HTML5表单错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!