使用jQuery手动触发表单验证

问题描述:

我有一个包含几个不同字段集的表单.我有一些jQuery,可以一次向用户显示字段集.对于支持HTML5验证的浏览器,我很乐意使用它.但是,我需要按我的意愿去做.我正在使用JQuery.

I have a form with several different fieldsets. I have some jQuery that displays the field sets to the users one at a time. For browsers that support HTML5 validation, I'd love to make use of it. However, I need to do it on my terms. I'm using JQuery.

当用户单击JS链接以移至下一个字段集时,我需要在当前字段集上进行验证,并在出现问题时阻止用户继续前进.

When a user clicks a JS Link to move to the next fieldset, I need the validation to happen on the current fieldset and block the user from moving forward if there is issues.

理想情况下,当用户失去对某个元素的关注时,就会进行验证.

Ideally, as the user loses focus on an element, validation will occur.

目前没有使用novalidate并使用jQuery.宁愿使用本机方法. :)

Currently have novalidate going and using jQuery. Would prefer to use the native method. :)

您无法触发本机验证UI (请参见下面的编辑),但是您可以轻松地在任意输入元素:

You can't trigger the native validation UI (see edit below), but you can easily take advantage of the validation API on arbitrary input elements:

$('input').blur(function(event) {
    event.target.checkValidity();
}).bind('invalid', function(event) {
    setTimeout(function() { $(event.target).focus();}, 50);
});

第一个事件一旦失去焦点,就会在每个输入元素上触发checkValidity,如果元素为invalid,则相应的事件将被第二个事件处理程序触发并捕获.这将焦点重新设置到元素上,但这可能很烦人,我想您有一个更好的通知错误的解决方案. 这是我上面的代码的有效示例.

The first event fires checkValidity on every input element as soon as it loses focus, if the element is invalid then the corresponding event will be fired and trapped by the second event handler. This one sets the focus back to the element, but that could be quite annoying, I assume you have a better solution for notifying about the errors. Here's a working example of my code above.

编辑:所有现代浏览器支持 此答案.

All modern browsers support the reportValidity() method for native HTML5 validation, per this answer.