Reputation: 2761
I'm using MVC3's Razor engine to generate views and have the following line of code generating a textbox
@Html.EditorFor(model => model.AddressLine1)
In the relevant model I'm using a data annotation attribute to limit the number of acceptable characters to 55:
[StringLength(55)]
public string AddressLine1 { get; set; }
However this allows the user to type in a longer address only to be then told via a validation message when they try and submit the form. How can I limit the textbox to 55 characters so that the user is unable to type any more than that in?
If I was generating the text box myself I would use the maxlength attribute for an input type but I'm not sure how to achieve the same results using the Html.EditFor method.
Upvotes: 7
Views: 33808
Reputation: 371
$('#AddressLine1').keypress(function(){
return this.value.length < 55
})
This jQuery function works on web browsers but on mobile this is not supported, so when creating a site being accessed by everyone consider that
Upvotes: 0
Reputation: 150253
@Html.TextBoxFor(model => model.AddressLine1, new {maxlength = 55})
maxlength
If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.
You can also use jQuery without changing the DOM:
$('#AddressLine1').keypress(function(){
return this.value.length < 55
})
Upvotes: 10
Reputation: 60493
Use maxlength
and a TextBoxFor
instead of EditorFor
EditorFor
has no overload that permit to do that.
This could be even more interesting for you : maxlength attribute of a text box from the DataAnnotations StringLength in Asp.Net MVC
Upvotes: 9