JQuery验证插件maxlength?

时间:2013-08-22 07:09:47

标签: javascript jquery html html5 jquery-validate

我正在使用JQuery验证插件。我想为其中一个字段指定maxlength。它可以指定如下。

rules: {
   Message: {
      required: false,
      maxLength: 200
   }
}

但是我没有在外部定义规则,而是想在html输入代码中指定规则

类似于:

<input type="text" name="AssistanPhone" value="" class="required"  />

在上面的例子中,“required”是通过类指定的。类似地,我如何指定jquery插件可以识别的maxlength,并在长度超过时给出错误消息?

谢谢!

4 个答案:

答案 0 :(得分:6)

不是资本Ll

例如:

$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      maxlength: 200
    }
  }
});

PLUGIN DEMO

答案 1 :(得分:4)

据我所知,您无法通过属性指定消息,但可以将maxlength指定为属性

<input type="text" name="AssistanPhone" value="" required maxlength="3"  />

演示:Fiddle

答案 2 :(得分:0)

我自己更新了验证器的javascript代码(所以我现在只使用我的1.8.1版而不是升级版),但这是我做的(第767行):

classRules: function(element) {
    var rules = {};
    var classes = $(element).attr('class');
    classes && $.each(classes.split(' '), function() {
        if (this in $.validator.classRuleSettings) {
            $.extend(rules, $.validator.classRuleSettings[this]);
        }
        if (this.toLowerCase().lastIndexOf('maxlength-', 0) === 0) { // starts with
            var x = parseInt(this.substring(10)); // take number after 'maxlength-'
            $.extend(rules, {maxlength: x});
        }
    });
    return rules;
},

我为&#34; maxlength - &#34;添加了额外的if-test,所以现在我可以添加类似&#34; maxlength-10&#34;限制为10.当然我也可以添加minlength等。

答案 3 :(得分:-1)


  $("#FormID").validate({
        rules: {
            PriorityDDL: {
                required: true
            },
            Title: {
                required: true
            },
            Text: {
                required: true,
                maxlength: 300
            },

            date: {
                required: true
            },
            reportfile: {
                required: true
            }
        },
        messages: {
            PriorityDDL: {
                required: "Please select priority"
            },
            Title: {
                required: "Please enter title"
            },
            Text: {
                required: "Please enter message",
                maxlength:"maxLength is 300 characters"
            },
            date: {
                required: "Please select date"
            },
            reportfile: {
                required: "Please select file"
            }
        }
    });