Text inputs with maxlength not validating with jQuery Validate

rdu*_*ont 8 jquery jquery-validate

I'm stuck with a problem using jQuery Validate. The thing is I have a few textboxes with their maxlength attributes set. Although they are not required, they still fail to validate when either empty or whitespace.

Sample HTML:

<input type="textbox" id="tbx1" maxlength="100" value="" />

Then, $('#tbx1').valid() returns false. Shouldn't it return true instead? Are there any known workarounds for this?

Oh, and adding $('#myform').validate({ ignore: '#tbx1' }); doesn't quite work for me, because I'm using ASP.NET controls with their automatic IDs. I know I could either use the control's client id or something like Wilco's IDOverride, but this is just not what I prefer.

So, anyone? Thanks!

Bru*_*uno 18

这似乎是这个插件中的一个错误.如果使用以下代码通过自定义实现替换方法来修复它:

$.validator.addMethod("maxlength", function (value, element, len) {
   return value == "" || value.length <= len;
});
Run Code Online (Sandbox Code Playgroud)


Phi*_*ger 0

首先,我假设输入有一个“name”属性,并且在您的示例中根本没有显示?如果没有,请尝试这样做,它可能会解决问题。

其次,您是否尝试过明确地将字段设置为不需要的字段,但在验证器对象中设置最大长度?例如:

var rules = {
  'txtbx1': {
    required: false,
    maxlength: '100'
  }
};

$('#formId').validate({rules:rules});
Run Code Online (Sandbox Code Playgroud)