2

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?

Matt V.
  • 9,703
  • 10
  • 35
  • 56

1 Answers1

2

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
  • 5,607
  • 6
  • 28
  • 52
  • 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:
    
        invalidHandler: function(){
          $(this.errorList[0].element).filter(":visible").focus();
        },
        focusInvalid: false
    
    . . . but I haven't been able to get that to work. Any further points? Thanks!
    – Matt V. Aug 05 '09 at 22:25
  • 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 Aug 06 '09 at 04:28