How to set maxlength for multiline TextBox?

2020-02-09 10:21发布

问题:

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.

回答1:

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.



回答2:

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());
}


回答3:

Hey pukipuki you can do as follows:

<asp:TextBox ID="txtValue" runat="server"TextMode="MultiLine" Rows="10"Columns="50"></asp:TextBox>

 $(document).ready(function(){ 
 var MaxLength = 250; 
 $('#txtValue').keypress(function(e) 
 { 
     if ($(this).val().length >= MaxLength)
 {    
    e.preventDefault();
 }  
 });});

You can see more in this following link: http://jquerybyexample.blogspot.in/2010/10/set-max-length-for-aspnet-multiline.html



回答4:

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();
        }
    });

}); 


回答5:

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.



回答6:

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)


回答7:

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()));
            }