Friday, September 6, 2013

Automatically add "maxlength" attribute to MVC validation textboxes

We needed the maxlength attribute added to all of our text boxes, but there was no obvious way to do it while using the built-in MVC validation.

I found this bit of JavaScript at that takes care of it automatically by adding the maxlength attribute to any input objects that contain the data-val-length-max attribute already.

<script type="text/javascript">
        function () {
                function (index) {
                    $(this).attr('maxlength', $(this).attr('data-val-length-max'));