如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:51:03  来源:igfitidea点击:

How to focus invalid fields with jQuery validate?

jqueryjquery-validate

提问by LA_

There is focusInvalidoption, which is trueby default. But it works only when form submission happens. If I validate the form with validmethod, then it doesn't work. So the question is how to focus invalid field when validis used?

focusInvalid选项,true默认情况下。但它只有在表单提交发生时才有效。如果我使用valid方法验证表单,则它不起作用。所以问题是如何在valid使用时聚焦无效字段?

Please see this demoto see the difference. Just press buttons there.

请参阅此演示以查看差异。只需按下那里的按钮。

回答by James Johnson

With the invalidHandleryou 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 focusInvalidfunction from the validatorvariable:

然后在验证处理程序中,您可以focusInvalidvalidator变量中手动调用该函数:

  $("#validate").click(function() {
        if ($("#test-form").valid()) 
              alert("Valid!");
        else
              validator.focusInvalid();

        return false;
  });

Example

例子