Geeks With Blogs

MOAR Objects Steve Wilkes' blog on .NET, Agile, TDD, design patterns and all that jazz

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!

Posted on Wednesday, October 3, 2012 5:58 PM ASP.NET MVC , ASP.NET , JQuery , JavaScript | Back to top


Comments on this post: Unobtrusive Maximum Input Lengths with JQuery and FluentValidation

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Steve Wilkes | Powered by: GeeksWithBlogs.net | Join free