Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add maxlength for TextAreaFor in View using razor engine

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?

like image 360
Kamil Avatar asked May 14 '12 15:05

Kamil


2 Answers

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.

MDN


Javascript(using jQuery) validation for HTML <5:

$('#EventNature').keypress(function(){
    if (this.value.length >= 10) // allowing you to enter only 10 chars.
    return false;        
});​

DEMO

like image 170
gdoron is supporting Monica Avatar answered Oct 15 '22 07:10

gdoron is supporting Monica


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" })
like image 42
Tom Stickel Avatar answered Oct 15 '22 07:10

Tom Stickel