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?

1
  • 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. Commented Apr 30, 2016 at 23:25

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

that is not what I was asking, I want to do that from the ValidationAttribute, not from the view.
I don't think that this is possible out of the box. You might want to look into this NuGet package. It allows you to insert custom HTML attributes based on the attributes present in your model. You can find some example usage here. Be warned though, it might be outdated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.