Jquery验证 - 单独事件的单独规则

时间:2015-12-17 23:23:40

标签: javascript jquery jquery-validate

我无法弄清楚如何使用jquery验证插件将单独的规则应用于单独的事件。我有自定义规则。我希望maxLen和formatVal在keyup上验证,但我希望minLen只在提交时验证。我怎样才能做到这一点?

$(document).ready(function () {



$.validator.addMethod(
    "maxLen", 
    function (value, element, param) {
      var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
      if (value.length > param) {
        return false;
      } else {
        return true;
      }
  }, "Please enter no more than {0} characters");

$.validator.addMethod(
    "minLen", 
    function (value, element, param) {
      var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
      if (value.length < param) {
        return false;
      } else {
        return true;
      }
  }, "Please enter at least {0} characters"); 

  $.validator.addMethod(
    "formatVal", 
    function (value, element) {
    return this.optional(element) || /^[a-z\d ]+$/i.test(value);
  }, "Letters and numbers only");




  $('#custom-tag').validate({
    debug: true,
    onkeyup: function (element, event) {
            var validator = $('#custom-tag').validate();
            if ( this.elementValue(element) === "") {
                validator.resetForm();
                return;
            } else {
                this.element(element);
            }
    },

    rules: {
      tag: {
        maxlength: 7,
        formatVal: true
      }
    }
  });



  });

Jsfiddle演示: http://jsfiddle.net/s6nas4gu/1/

0 个答案:

没有答案