Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting the length of characters in a textbox while using Razor's Html.EditFor

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.

like image 984
Sperick Avatar asked Jun 29 '12 13:06

Sperick


2 Answers

 @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
})
like image 200
gdoron is supporting Monica Avatar answered Nov 12 '22 10:11

gdoron is supporting Monica


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

like image 23
Raphaël Althaus Avatar answered Nov 12 '22 10:11

Raphaël Althaus