|
| 1 | +--- |
| 2 | +title: Add max-length validation |
| 3 | +page_title: Add max-length validation |
| 4 | +description: Add max-length validation |
| 5 | +--- |
| 6 | + |
| 7 | +# Add max-length validation |
| 8 | + |
| 9 | +The snippet below demonstrates how to define custom kendo validators to check the length of the text content, or the length of the HTML content, via custom validation rules. |
| 10 | + |
| 11 | +#### Example |
| 12 | + |
| 13 | + <form> |
| 14 | + @(Html.Kendo().Editor() |
| 15 | + .Name("editor") |
| 16 | + .HtmlAttributes(new { data_maxtextlength="50", data_maxtextlength_msg="Text must be shorter than 50 chars" }) |
| 17 | + .Value("Lorem ipsum dolor sit amet. Lorem ipsum dolor sit.") |
| 18 | + ) |
| 19 | + |
| 20 | + <button class="k-button k-primary">Submit</button> |
| 21 | + </form> |
| 22 | + |
| 23 | + <script> |
| 24 | + |
| 25 | + // register custom validation rules |
| 26 | + (function ($, kendo) { |
| 27 | + $.extend(true, kendo.ui.validator, { |
| 28 | + rules: { |
| 29 | + maxTextLength: function (textarea) { |
| 30 | + if (textarea.is("[data-maxtextlength-msg]") && textarea.val() != "") { |
| 31 | + var maxlength = textarea.attr("data-maxtextlength"); |
| 32 | + var value = textarea.data("kendoEditor").value(); |
| 33 | + return value.replace(/<[^>]+>/g, "").length <= maxlength; |
| 34 | + } |
| 35 | + |
| 36 | + return true; |
| 37 | + }, |
| 38 | + maxHtmlLength: function (textarea) { |
| 39 | + if (textarea.is("[data-maxhtmllength-msg]") && textarea.val() != "") { |
| 40 | + var maxlength = textarea.attr("data-maxhtmllength"); |
| 41 | + var value = textarea.data("kendoEditor").value(); |
| 42 | + return value.length <= maxlength; |
| 43 | + } |
| 44 | + |
| 45 | + return true; |
| 46 | + } |
| 47 | + } |
| 48 | + }); |
| 49 | + |
| 50 | + $("form").kendoValidator(); |
| 51 | + })(jQuery, kendo); |
| 52 | + </script> |
| 53 | + |
0 commit comments