Let’s say I have a property in model with maximum string length is specified, like this:
[Required, StringLength(100)]
public string Name { get; set; }
Then on my razor page I have this:
<input asp-for="Customer.Name" />
Which is then rendered like this:
<input name="Customer.Name"
id="Customer_Name"
type="text"
value=""
data-val-required="The Name field is required."
data-val-length-max="100"
data-val-length="The field Name must be a string with a maximum length of 100."
data-val="true">
There is validation logic there to check that the string isn’t more than 100 characters, that’s good. But couldn’t the maxlength=”100” attribute in the input-tag be added as well, so it’s not even possible to enter more characters than the limit?
It’s quite easy to do a custom TagHelper that takes care of this:
https://stackoverflow.com/questions/43477621/maxlength-annotation-to-maxlength-input-property
But I wonder why this isn’t in the core from start. It looks obvious to me but I’m sure I’m missing something :-)
Thanks for contacting us, @pekspro.
@NTaylorMullen, are you aware of any reason we didn't do this? Not having any insights looks like a reasonable ask to me.
@dougbu this seems reasonable. Is there a reason why we didn't do this in the past?
@NTaylorMullen this probably wasn't done because it felt redundant w.r.t. the client-side validations.
It's also possible that the experience when the user types the 101st character would degrade. I'm not sure what browsers tend to do when an <input/> element's limit is reached. By "degrade", I mean an error might result in a pop-up or message somewhere other than the generated locations.
Browsers just do not allow typing in more than the limit. I like this idea and am preparing a PR to handle this.
Just a note here, there's more similar attributes described at https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation, range (or RangeAttribute) for one. It looks to me there's more into this at https://github.com/aspnet/Mvc/issues/7035 (and at https://github.com/aspnet/Mvc/issues/7035#issuecomment-406895066).
Most helpful comment
Browsers just do not allow typing in more than the limit. I like this idea and am preparing a PR to handle this.