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

前端 未结 16 665
野趣味
野趣味 2020-12-04 16:12

I\'m using the excellent jquery.validation plugin by Jörn Zaefferer and I was wondering whether there\'s a easy way to automatically trim form elements before they are valid

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 17:03

    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.

提交回复
热议问题