How to focus invalid fields with jQuery validate?

后端 未结 2 1062
耶瑟儿~
耶瑟儿~ 2021-01-30 10:13

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 w

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 11:07

    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:

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

    Example

提交回复
热议问题