1

I have what seems to be a simple task but I'm having trouble figuring out how to do it.

I have a form that is validating with the jquery validate plugin. I have a custom validation which validates that you have all valid ascii characters in a text/textarea field, and we hook that in to any field with the class "ascii" using the $.validator.addMethod() functionality.

My issue is that I want to keep the validation, but I also have a separate short javascript function which cleans up those garbage characters. I want to run the cleanup on the input field before the validation complains that it's invalid.

I tried putting the cleanup into the validation method before it returns true or false, that didn't work. I tried binding it to the blur event, that didn't work.

Binding it to the keyup event works, but I feel like that's a hack. I just want it to do it's thing and have that thing be tied in with the validation so that it knows to cleanup before it checks the validity of that field.

I found a jquery extension called bindFirst here: How to order events bound with jQuery

and tried binding the cleanup "first" to the blur event, but that didn't work.

I think I can pull of what I need using the "depends" functionality, but that doesn't seem to be an option when using custom validations.

In all the scenarios I mentioned.. it does perform the cleanup, but not until it already complained that the field is invalid. Simply going back to the field and back out erases the error message.

Any help would be appreciated.

Community
  • 1
  • 1
MoDiggity
  • 261
  • 2
  • 10

1 Answers1

1

You simply need to leverage one of the Validate plugin's built-in callback functions. If you want to use onfocusout, then modify the default onfocusout callback function.

default onfocusout callback:

onfocusout: function( element, event ) {
    if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
         this.element(element);
    }
}

Suggested Usage:

Notice how the core functionality is preserved as to not interfere with the other fields.

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        // rules & options,
        onfocusout: function (element, event) {
            if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
                if (element.name == "yourfield") {
                    // your code to do cleanup on name="yourfield"
                }
                this.element(element);  // <-- this triggers validation on the field
            }
        }
    });

});

Working Demo: http://jsfiddle.net/WTjTy/

Demo will trigger a mock "clean-up", just before any error is displayed, on blur of the specified input field.

Sparky
  • 98,165
  • 25
  • 199
  • 285