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 http://sharpercoder.blogspot.com/2011/04/validation-set-maxlength-of-text-box.html 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">
    $(document).ready
    (
        function () {
            $('input[data-val-length-max]').each
            (
                function (index) {
                    $(this).attr('maxlength', $(this).attr('data-val-length-max'));
                })
        });
</script>