如何使用 jQuery 验证聚焦无效字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10111907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to focus invalid fields with jQuery validate?
提问by LA_
There is focusInvalid
option, which is true
by default. But it works only when form submission happens. If I validate the form with valid
method, then it doesn't work. So the question is how to focus invalid field when valid
is used?
有focusInvalid
选项,true
默认情况下。但它只有在表单提交发生时才有效。如果我使用valid
方法验证表单,则它不起作用。所以问题是如何在valid
使用时聚焦无效字段?
Please see this demoto see the difference. Just press buttons there.
请参阅此演示以查看差异。只需按下那里的按钮。
回答by James Johnson
With the invalidHandler
you can set focus to the first element that fails:
使用invalidHandler
可以将焦点设置到第一个失败的元素上:
$("#form").validate({
onfocusout: false,
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
validator.errorList[0].element.focus();
}
}
});
回答by Rory McCrossan
First of all you need to save your validator to a variable so you can use it in the click handler:
首先,您需要将验证器保存到一个变量中,以便您可以在点击处理程序中使用它:
var validator = $("#test-form").validate({ /* settings */ });
Then in the validate handler, you can manually call the focusInvalid
function from the validator
variable:
然后在验证处理程序中,您可以focusInvalid
从validator
变量中手动调用该函数:
$("#validate").click(function() {
if ($("#test-form").valid())
alert("Valid!");
else
validator.focusInvalid();
return false;
});