Thursday 2 November 2017

MVC - How to add MaxLength to TextBoxFor or other controlls using data annotations

watch this example on YouTube


1. Metadata

        [StringLength(3, ErrorMessage ="{0} cannot be longer than 3 chars")]
        public string Name { get; set; }

2. Javascript

$(document).ready(function () {
    $('input[data-val-length-max]').each(
        function (index) {
            $(this).attr('maxlength', $(this).attr('data-val-length-max'));

        });
});

3. Layout

    @Scripts.Render("~/Scripts/MaxLength.js")

No comments:

Post a Comment