HTMLInputElement: invalid event - Web APIs 编辑

The invalid event fires when a submittable element has been checked for validity and doesn't satisfy its constraints.

BubblesNo
CancelableYes
InterfaceEvent
Event handler propertyGlobalEventHandlers.oninvalid

This event can be useful for displaying a summary of the problems with a form on submission. When a form is submitted, invalid events are fired at each form control that is invalid. The validity of submittable elements is checked before submitting their owner <form>, or after the checkValidity() method of the element or its owner <form> is called.

It is not checked on blur.

Examples

If a form is submitted with an invalid value, the submittable elements are checked and, if an error is found, the invalid event will fire on the invalid element. In this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged.

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
}

Result

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'Invalid event' in that specification.
Living Standard
HTML 5.1
The definition of 'Invalid event' in that specification.
Recommendation
HTML5
The definition of 'Invalid event' in that specification.
Recommendation

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:171 次

字数:4530

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文