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?
Set the attribute using a MVC 5 Razor HTML helper.
@Html.TextBoxFor(m => m.Name, new {maxlength = "10"})
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.