views:

924

answers:

1

I am using the jquery form validation plugin to validate a long form. If a user submits the form with multiple fields that fail to validate, the cursor returns to the last field that did not pass. Instead, I want the cursor to be returned to the first field in the form that failed validation. Rather than modifying the plugin, I would like to override focusInvalid, which is nested inside "prototype: {...}":

focusInvalid: function() {
    if( this.settings.focusInvalid ) {
     try {
      $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus();
     } catch(e) {
      // ignore IE throwing errors when focusing hidden elements
     }
    }
},

I've tried adding my own version of focusInvalid within the following, but I haven't been able to get that to work:

$("form#user-register").validate({. . .});

Any pointers?

+1  A: 

You can disable the selection of the first invalid input with the focusInvalid option. You can then use the invalidHandler option to set a custom function that selects the first element in your form. The invalidHandler option is the function that the plugin calls when an invalid form is submitted.

Example below:

$("form#user-register").validate({
     invalidHandler: function(form, validator){
         $(validator.invalidElements()[0]).focus();
     },
     focusInvalid:false
});
MitMaro
Thanks, I didn't know about invalidHandler. The code above is close to what I need; however, I'd like the user to be returned to the first *invalid* field.I thought it would be something along the lines of:<pre><code> invalidHandler: function(){ $(this.errorList[0].element).filter(":visible").focus(); }, focusInvalid: false</pre></code>. . . but I haven't been able to get that to work. Any further points?Thanks!
Matt V.
Updated. You were on the right track with what you were doing. You can still filter use the `:visible` filter if you want but it would only be needed if you are validating hidden inputs.
MitMaro
That's exactly what I needed. Thanks a lot!
Matt V.