1

In mvc5 whenever you use [MaxLength(10)] attribute it generates the following html attribute:

`data-val-maxlength="The field Email must be a string or array type with a maximum length of '10'."

This is nice and useful and all but what I wish to do is to prevent user from being able to type after they hit the maximum length. To do that I can use html attribute maxlength Now, what I am trying to figure out is how can I inject a custom attribute into the html field without it having a prefix of data-val-

I tried doing this through IClientValidatable but that generates the data-val- prefix. Is this possible?

Bagzli
  • 6,254
  • 17
  • 80
  • 163
  • You cannot do this through `IClientValidatable` (the whole purpose of `IClientValidatable` is to add the `data-val-*` attributes used by `jquery.validate.unobtrusive.js` to add rules to the jQuery validator. –  Apr 30 '16 at 23:25

1 Answers1

1

1. MVC5 Razor

Set the attribute using a MVC 5 Razor HTML helper.

@Html.TextBoxFor(m => m.Name, new {maxlength = "10"})

2. Clientside script

You can move the value from the generated attribute to the html attribute using some Javascript code (this example uses jQuery).

$("input[data-val-maxlength]").each(function (index, element) {
   var length = parseInt($(this).data("val-maxlength"));
   $(this).prop("maxlength", length);
});
Elias Meire
  • 1,238
  • 1
  • 11
  • 14
  • that is not what I was asking, I want to do that from the `ValidationAttribute`, not from the view. – Bagzli Apr 30 '16 at 21:55
  • I don't think that this is possible out of the box. You might want to look into this [NuGet package](http://www.nuget.org/packages/UkadcHtmlAttributeProvider/). It allows you to insert custom HTML attributes based on the attributes present in your model. You can find some example usage [here](https://blogs.msdn.microsoft.com/stuartleeks/2012/05/24/asp-net-mvc-supplying-html-attributes-with-editorfor/). Be warned though, it might be outdated. – Elias Meire Apr 30 '16 at 23:09