你能用 JavaScript 触发自定义 HTML5 表单错误吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8597595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you trigger custom HTML5 form errors with JavaScript?
提问by Oscar Godson
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');
如果我有一个像这样的输入<input type="text">
并且我想在输入上触发一个本机错误,你能做到吗?喜欢(伪代码)ele.triggerError('Error Message');
It would then look like:
然后它看起来像:
(source: tylergaw.com)
(来源:tylergaw.com)
But with a custom message and for it's own validation function. Needed for AJAX validations for example.
但是带有自定义消息和它自己的验证功能。例如,需要 AJAX 验证。
回答by robertc
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 exampleyou can play around with to verify.
触发本机错误的唯一方法是提交表单。尽管您可以使用setCustomValidity
(如我在此处的回答中所述)设置自定义消息, 并且您可以使用 触发invalid
事件checkValidity
,但这仅提供挂钩以供您创建自己的验证 UI。 这是一个简单的示例,您可以使用它进行验证。
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 submitbutton that will work in Firefox and Opera, but not Chrome. I'd avoid doing it right now.
请注意,如果您使用submit()
将绕过验证 API的方法提交表单。但是,如果您触发click
提交按钮的事件,该事件将在 Firefox 和 Opera 中起作用,但在 Chrome 中不起作用。我会避免现在这样做。
回答by Peter Umoren
You can now use the HTMLFormElement.reportValidity()
method, at the moment it's implemented in Chrome, Firefox, Opera, and Android browsers, but not supported in Internet Explorer (check caniuse.comto see supported browsers).
您现在可以使用该HTMLFormElement.reportValidity()
方法,目前它已在 Chrome、Firefox、Opera 和 Android 浏览器中实现,但在 Internet Explorer 中不受支持(请访问 caniuse.com查看支持的浏览器)。