Unobtrusive Maximum Input Lengths with JQuery and FluentValidation

Posted by Steve Wilkes on Geeks with Blogs See other posts from Geeks with Blogs or by Steve Wilkes
Published on Wed, 03 Oct 2012 15:58:34 GMT Indexed on 2012/10/03 21:38 UTC
Read the original article Hit count: 269

Filed under:

If you use FluentValidation and set a maximum length for a string or a maximum  value for a numeric property, JQuery validation is used to show an error message when the user inputs too many characters or a numeric value which is too big. On a recent project we wanted to use input’s maxlength attribute to prevent a user from entering too many characters rather than cure the problem with an error message, and I added this JQuery to add maxlength attributes based on JQuery validation’s data- attributes.

$(function () {
    $("input[data-val-range-max],input[data-val-length-max]").each(function (i, e) {
        var input = $(e);
        var maxlength = input.is("[data-val-range-max]")
            ? input.data("valRangeMax").toString().length
            : input.data("valLengthMax");
        input.attr("maxlength", maxlength);
    });
});

Presto!

© Geeks with Blogs or respective owner