Timur Sadykov
Timur Sadykov

Reputation: 11377

How to set maxlength for multiline TextBox?

When using a MultiLine TextBox (which generates a TextArea) setting the MaxLength property has no effect. What is the best workaround? I'd like to get basic, intended functionality with minimum of ugly javascript etc. Just prevent user from entering more than max number of characters.

Upvotes: 11

Views: 55949

Answers (6)

Jim B
Jim B

Reputation: 459

To force asp.net to send the maxlength attribute for all multiline textboxes on a page or a whole site, building on Aximili's answer above:

  1. Create a function to get all the controls on the page:

I use the control extension method from David Findley https://weblogs.asp.net/dfindley/linq-the-uber-findcontrol and referenced in this SO post Loop through all controls on asp.net webpage

namespace xyz.Extensions
{
    public static class PageExtensions
    {
        public static IEnumerable<Control> All(this ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                foreach (Control grandChild in control.Controls.All())
                    yield return grandChild;

                yield return control;
            }
        }
    }
}
  1. In the page or master page

Make sure to reference the namespace for the extension method in step 1.

Put the following code in the Page_Load function:

if (!IsPostBack){
    //force textareas to display maxlength attribute 
    Page.Controls.All().OfType<TextBox>().ToList()
                    .Where(x => x.TextMode == TextBoxMode.MultiLine && x.MaxLength > 0)
                    .ToList().ForEach(t => t.Attributes.Add("maxlength", t.MaxLength.ToString()));
            }

Upvotes: 0

Yash
Yash

Reputation: 1

Try this..

    Dim script As String = ""

    script = script + " <script type='text/javascript'> function CheckLength(obj) {"
    script = script + "  var object = document.getElementById(obj);"
    script = script + " if (object.value.length > 5) {"
    script = script + "     object.focus();"
    script = script + "      object.value = object.value.substring(0, 5); "
    script = script + "      object.scrollTop = object.scrollHeight; "
    script = script + "      return false;"
    script = script + "   }"
    script = script + "   return true;"
    script = script + "   }</script>"


    Dim b As New TextBox()
    b.ID = "btnSomeButton"
    b.TextMode = TextBoxMode.MultiLine
    Mypanel.Controls.Add(b)
    b.Attributes.Add("onkeyup", "return CheckLength('" & b.ClientID & "');")

    Page.ClientScript.RegisterStartupScript(Page.GetType(), "key", script, False)

Upvotes: 0

Vinc 웃
Vinc 웃

Reputation: 1247

Here's a cross browser solution :

<asp:TextBox TextMode="MultiLine" runat="server" ID="txtPurpose" Columns="50" Rows="2" onkeypress="return isokmaxlength(event,this,255);" ClientIDMode="static"></asp:TextBox>

Javascript :

function isokmaxlength(e,val,maxlengt) {
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode

    if (!(charCode == 44 || charCode == 46 || charCode == 0 || charCode == 8 || (val.value.length < maxlengt))) {
        return false;
    }
}

You have to think about the Copy and Paste. This is a little bit tricky, I simply disable it with Jquery. But you can create your own function to do more complex verification. But in my case, copy and paste is not allowed.

Jquery to disable copy and paste :

jQuery(function ($) {

    $("#txtPurpose").bind({
        paste: function (e) {
            e.preventDefault();
        }
    });

}); 

Upvotes: 3

Aximili
Aximili

Reputation: 29444

If you don't care about older browsers (see supported browsers here),
you can set MaxLength normally like this

<asp:TextBox ID="txt1" runat="server" TextMode="MultiLine" MaxLength="100" />

and force it to be printed out to the HTML

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
    txt1.Attributes.Add("maxlength", txt1.MaxLength.ToString());
}

Upvotes: 27

xplat
xplat

Reputation: 8626

If you are using a model object bind to that textbox you can use DataAnnotations attributes to set the maxlength of that property. I'm based on MVC about that but it should work for ASP.NET too!

This way you don't mess with any Javascript or setting anything in the markup.

Upvotes: 1

Claudio Redi
Claudio Redi

Reputation: 68400

If you want to let the user know if he exceeded the amount of characters as he writes, you could use a javascript function attached to keypress event. This function would test the length of the input and cancel the character rendering if the maxlenght was reached.

Another option is to use RegularExpressionValidator control to validate the input on submit.

In my opinion, the first option is much more better.

I'm not adding any code since google is full of examples for all tastes, this is a very common task.

Here you have a sample search that might help.

Upvotes: 5

Related Questions