使用 jQuery 手动触发表单验证 [英] Manually Triggering Form Validation using jQuery

查看:34
本文介绍了使用 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.

目前没有使用 jQuery 的验证.更愿意使用本机方法.:)

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

推荐答案

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

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.

所有现代浏览器支持reportValidity() 用于原生 HTML5 验证的方法,每这个答案.

这篇关于使用 jQuery 手动触发表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆