MaxLength Attribute not generating client-side validation attributes

I have a curious problem with ASP.NET MVC3 client-side validation. I have the following class:

public class Instrument : BaseObject
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Name is required.")]
    [MaxLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
    public string Name { get; set; }
}

From my view:

<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>

And here's the generated HTML I get for the textbox for this field:

<input class="text-box single-line" data-val="true" data-val-required="Name is required." id="Name" name="Name" type="text" value="">

No sign of the MaxLengthAttribute, but everything else seems to be working.

Any ideas what's going wrong?


Try using the [StringLength] attribute:

[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }

That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.


I just used a snippet of jquery to solve this problem.

$("input[data-val-length-max]").each(function (index, element) {
   var length = parseInt($(this).attr("data-val-length-max"));
   $(this).prop("maxlength", length);
});

The selector finds all of the elements that have a data-val-length-max attribute set. This is the attribute that the StringLength validation attribute will set.

The each loop loops through these matches and will parse out the value for this attribute and assign it to the mxlength property that should have been set.

Just add this to you document ready function and you are good to go.