How to focus invalid fields with jQuery validate?

LA_ picture LA_ · Apr 11, 2012 · Viewed 70.7k times · Source

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.

Answer

James Johnson picture James Johnson · Apr 11, 2012

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();
        }
    } 
});