how to add maxlength for TextAreaFor in View using razor engine
Solution 1
You can do it like:
@Html.TextArea("EventNature",new { maxlength=50, // or other value
style = "width: 200px; height: 100px;" })
Just be aware it's an HTML5 attribute
maxlength HTML5
The maximum number of characters (Unicode code points) that the user can enter. If it is not specified, the user can enter an unlimited number of characters.
Javascript(using jQuery) validation for HTML <5:
$('#EventNature').keypress(function(){
if (this.value.length >= 10) // allowing you to enter only 10 chars.
return false;
});
Solution 2
This also works for the TextAreaFor helper with more than one anonymous type in new
Confirmed to work fine in Visual Studio 2015 with MVC 5
@Html.TextAreaFor(model => model.Comments, 5, 500, new {maxlength=4000, @class = "form-control" })
Solution 3
You can also restrict the length of textbox, like this:
<textarea id="EventNature1" maxlength="10"></textarea>
OR
@Html.TexareaFor(m=>m.Name,new{@maxlength="10"})
Kamil
I'm a Technical Lead currently based in Chennai. I have about 10 years of experience working with Web Application primarily using Microsoft Technologies. Throughout my career I have worked in all phases of SDLC viz., Requirement Analysis, Solution Design, Implementation, Testing, Deployment and Maintenance phases. Being a US work permit holder, I have experience in working with Clients onsite. Outside of work I’m a keen techy always on the look out for latest technologies around the horizon.
Updated on October 05, 2020Comments
-
Kamil over 3 years
I have a TextArea() control in my View implemented using Razor Engine.
@Html.TextArea("EventNature",new { style = "width: 200px; height: 100px;" })
How can i set the Maxlength attribute for this control?
is there any built in Attribute in RazorEngine or do i have to use scripts?-
gdoron is supporting Monica about 12 yearsNote that you don't use
TextAreaFor
in your question...
-
-
gdoron is supporting Monica about 12 yearsIt's not true. maxlength is an HTML5 attribute.
-
Kamil about 12 yearsThnx... any way i've to use Javascript for the validation when it comes to HTML5 incompatible browsers rite?
-
Kamil about 12 yearsany link where i can follow-up for the javascript validation, coz i haven't used Js with Razor ;)
-
gdoron is supporting Monica about 12 years@Kamil. Didn't get your question.
-
gdoron is supporting Monica about 12 years@Kamil. Just the way you did. But you better use
TextAreaFor
-
MCollard almost 3 yearsThe script doesn't work when you copy/paste text into the TextArea
-
gdoron is supporting Monica almost 3 years@MCollard use same code, replace\add
keypress
withmouseup
event. -
gdoron is supporting Monica almost 3 yearsThis is an extremely old answer, and I don't use this website anymore. But I was pointed to it again, see here: developer.mozilla.org/en-US/docs/Web/HTML/Element/…