Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 304
rdumont Avatar asked Jul 29 '10 17:07

rdumont


2 Answers

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;
});
like image 65
Bruno Avatar answered Sep 20 '22 11:09

Bruno


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
        }
 }
like image 28
Chris Avatar answered Sep 18 '22 11:09

Chris