jquery.validate plugin - how to trim values before form validation

This code works for me. I haven't used it much so there may be bugs.

It wraps each method and trims the first element which is value.

(function ($) {

    $.each($.validator.methods, function (key, value) {
        $.validator.methods[key] = function () {           
            if(arguments.length > 0) {
                arguments[0] = $.trim(arguments[0]);
            }

            return value.apply(this, arguments);
        };
    });
} (jQuery));

if you're using select2 and validation at the same time, I recommend to put el.val($.trim(el.val())); inside an IF like this: if(el.prop('type') != 'select-multiple'){el.val($.trim(el.val()));}. That way, your jquery validation will behave as expected, and it will let you select multiple items.


Since I want this behavior on all my forms by default I decided to modify the jquery.validate.js file. I applied the following change to onfocusout method:

Original:

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

To:

onfocusout: function (element, event) {
    if (element.tagName === "TEXTAREA" || (element.tagName === "INPUT" && element.type !== "password")) {
        element.value = $.trim(element.value);
    }
    if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
        this.element(element);
    }
}

I do want to allow spaces at the begging and end of password.

autoTrim could be added as a property to options.


I did this with success.

Instead of:

Email: { required: true, email: true }

I did this:

Email: {
    required: {
        depends:function(){
            $(this).val($.trim($(this).val()));
            return true;
        }
    },
    email: true
}