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

前端 未结 16 714
野趣味
野趣味 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

    I like the approach by xuser (https://stackoverflow.com/a/10406573/80002), however, I do not like messing with the plugin source code.

    So, I suggest doing this instead:

     function injectTrim(handler) {
      return function (element, event) {
        if (element.tagName === "TEXTAREA" || (element.tagName === "INPUT" 
                                           && element.type !== "password")) {
          element.value = $.trim(element.value);
        }
        return handler.call(this, element, event);
      };
     }
    
    
     $("form").validate({
        onfocusout: injectTrim($.validator.defaults.onfocusout)
     });
    

提交回复
热议问题