触发HTML5表单验证 [英] Triggering HTML5 Form Validation

查看:314
本文介绍了触发HTML5表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个不同字段集的表单。我有一些Javascript一次显示字段集的用户。对于支持HTML5验证的浏览器,我很乐意使用它。但是,我需要按照我的条件来做。我正在使用JQuery。



当用户点击JS链接移动到下一个字段集时,我需要在当前字段集上进行验证并阻止用户如果有问题,请继续前进。



理想情况下,当用户失去对元素的关注时,将进行验证。



<目前没有使用JavaScript的验证码。宁愿使用本地方法。 :)

解决方案

您无法触发本机验证用户界面,但您可以轻松利用任意输入的验证API元素:

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

第一个事件在每次输入时触发 checkValidity 元素一旦失去焦点,如果元素是 invalid ,那么相应的事件将被第二个事件处理程序触发并捕获。这一点将重点放在元素上,但这可能很烦人,我假设你有更好的解决方案来通知错误。 以上是我上面代码的一个工作示例


I have a form with several different fieldsets. I have some Javascript 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.

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.

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

解决方案

You can't trigger the native validation UI, 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);
});

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.

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

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