How to focus invalid fields with jQuery validate?

JqueryJquery Validate

Jquery Problem Overview


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?

Please see this demo to see the difference. Just press buttons there.

Jquery Solutions


Solution 1 - Jquery

With the invalidHandler you can set focus to the first element that fails:

$("#form").validate({
    onfocusout: false,
    invalidHandler: function(form, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {                    
            validator.errorList[0].element.focus();
        }
    } 
});

Solution 2 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLA_View Question on Stackoverflow
Solution 1 - JqueryJames JohnsonView Answer on Stackoverflow
Solution 2 - JqueryRory McCrossanView Answer on Stackoverflow