Wednesday, May 22, 2013

Setup maxlength for strings in ASP.NET MVC

String length is an attribute available in the System.ComponentModel.DataAnnotations; namespace for your viewmodels. It sets up validation for max length e.g:

[StringLength(100, ErrorMessage = "Length must be less than or equal to 100")]

In html this will warn the user if the length exceeds 100. But if you want the html input to disallow the user to even type more than 100 characters then that functionality is not provided out of the box. You can use the attribute added to the html tag because of StringLength ie. data-val-length-max to add the maxlength attribute using one line of jquery:

$('[data-val-length-max]').each(function () { $(this).attr("maxlength", $(this).attr('data-val-length-max')); });

The maxlength attribute prevents the user from entering more characters than are allowed. This one line does it for all inputs that have this attribute setup in a view.