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

31,264

Solution 1

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

Solution 2

 @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
})
Share:
31,264
Sperick
Author by

Sperick

Software Developer

Updated on August 17, 2022

Comments

  • Sperick
    Sperick over 1 year

    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.