rdumont
rdumont

Reputation: 563

Text inputs with maxlength not validating with 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!

Upvotes: 10

Views: 23701

Answers (3)

Bruno
Bruno

Reputation: 1263

This seems to be a bug in this plugin. If fixed it by replacing the method by a custom implementation using the following code:

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

Upvotes: 20

Chris
Chris

Reputation: 31

Ran into this problem myself on some complex forms I was writing...

My solution is just to create my own maxlength method that I can 'maxLen' that works almost exactly like the default method just under a different name. Just paste this above your main validate call ($("#mainform").validate({}); or whatever your form is called).

//Custom Max Length Validation
jQuery.validator.addMethod("maxLen", function (value, element, param) {
    //console.log('element= ' + $(element).attr('name') + ' param= ' + param )
    if ($(element).val().length > param) {
        return false;
    } else {
        return true;
    }
}, "You have reached the maximum number of characters allowed for this field.");

Once you've done that you can add the rule like so:

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

Upvotes: 3

Philip Schweiger
Philip Schweiger

Reputation: 2734

First, I assume that the input has a "name" attribute and is simply not shown in your example? If not, try that and it may fix the issue.

Second, have you tried explicitly setting the field to be not required but to have a maxlength in the validator object? For instance:

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

$('#formId').validate({rules:rules});

Upvotes: 0

Related Questions