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!
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;
});
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With