Jquery validation plugin maxlength?

I am using the jQuery validation plugin. I want to specify maxlength for one of the fields. It can be specified as shown below.

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

But instead of defining the rules from the outside, I want to specify the rules inside the html input code

Similarly:

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

In the above example, β€œrequired” is indicated through the class. In the same way as I can specify maxlength which can be recognized by the jquery plugin and gives an error message if the length exceeds?

Thanks!

+4
source share
3 answers

Not capital L his L

Example:

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

Plugin demo

+4
source

As far as I see, you cannot specify messages through attributes, but maxlength can be specified as an attribute

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

Demo: Fiddle

+3
source

I myself updated the validator JavaScript validation code (so instead of updating it, I now stick to my version 1.8.1), but here's what I did (around line 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; }, 

I added an extra if-test for "maxlength-", so now I can add a class such as "maxlength-10" to limit 10. Of course, I could also add minlength, etc.

0
source

Source: https://habr.com/ru/post/1498320/


All Articles