若一个可提交元素在检查有效性时,不符合对它的约束条件,则会触发 invalid
事件。
冒泡 | 否 |
---|---|
可取消 | 是 |
接口 | Event |
事件处理程序属性 | GlobalEventHandlers.oninvalid |
这个事件可用于展示提交表单时所出现的问题的概览。当表单提交时,若任一表单控件无效,则会触发 invalid
事件。对可提交元素有效性的检查是在提交父元素 <form>
之前或调用父元素 <form>
或元素自己的 checkValidity()
方法之后。
这个事件不会在 blur
事件中触发。
示例
如果表单提交时有无效值,检查可提交元素时发现了错误,则 invalid
事件会在那个无效元素上触发。在这个例子中,当输入无效值触发 invalid
事件时,这个无效值被记录下来。
HTML
<form action="#">
<ul>
<li><label>Enter an integer between 1 and 10: <input type="number" min="1" max="10" required></label></li>
<li><input type="submit" value="submit"></li>
</ul>
</form><p id="log"></p>
JavaScript
const input = document.querySelector('input')
const log = document.getElementById('log')
input.addEventListener('invalid', logValue)
function logValue(e) {
log.textContent += e.target.value
}
结果
规范
规范 | 状态 | 注释 |
---|---|---|
HTML Living Standard Invalid event |
Living Standard | |
HTML 5.1 Invalid event |
Recommendation | |
HTML5 Invalid event |
Recommendation |
浏览器兼容性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
参见
- HTML
<form>
元素 - 相关事件:
submit
- CSS
:invalid
伪类