55

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.

LA_
  • 19,823
  • 58
  • 172
  • 308
  • 1
    @Evan, don't you like jsbin? You can modify that as well - http://jsbin.com/ayupob/edit#javascript,html – LA_ Apr 11 '12 at 19:02

2 Answers2

67

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();
        }
    } 
});
James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • 3
    jQuery validate selects the first invalid element **or the last focused invalid element**. Your code is the only I've found that dodges this annoyance and always selects the first. Thank you! – Preston Badeer Mar 26 '13 at 14:33
  • 2
    Yeah there is a lot a snafus that affect jquery.validates focus handling. By itself it works like a top but when you start adding in responsive designs and more jquery scripts, the focus can get somewhat off. Nice script, thanks for posting it. – isaac weathers Mar 12 '14 at 21:46
  • +1 for this option, couldn't find it anywhere. BTW, a small tip: also do `validator.lastActive = validator.errorList[0].element;` to avoid focussing on two elements.. this was something I faced with `end date` field as last active and `start date` as first invalid field, datepickers popped up on both fields (of course both were invalid). Cheers!! – Fr0zenFyr Apr 01 '17 at 07:29
56

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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339