25
<asp:TextBox ID="txtBodySMS" runat="server" Rows="10"                          
           TextMode="MultiLine" Width="100%"></asp:TextBox>

This is my text box. How do I limit the number of characters a user can type inside it?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Beginner
  • 28,539
  • 63
  • 155
  • 235

13 Answers13

27

MaxLength does not apply to ASP.NET to Textboxes with TextMode="MultiLine". An easy way to do this and keep your MultiLine mark up would be to add:

onkeypress="return this.value.length<=10" 

with 10 being the limit. Like so:

<asp:TextBox ID="txtBodySMS" runat="server" Rows="10" onkeypress="return this.value.length<=10" TextMode="MultiLine" Width="100%"></asp:TextBox>

 

EDIT Option One (Server side) The above example has some issues pointed out over the years. The underlying problem is a multi-line textBox is rendered as a text-area and MaxLength is removed. We can also fix in the C# or VB asp.net code behind of the page by forcing the re-attachment of MaxLength instead of attaching onkeypress.

    protected void Page_Load(object sender, EventArgs e)
    {
        txtBodySMS.Attributes.Add("maxlength", "10");
    }

EDIT Option Two (Client side): Here's a simple jquery solution. Include the following script in your head instead of attaching onkeypress or editing the server side code.

    $(document).ready(function () {
        $(".MultiLineLimit").on('change keydown paste input', function () {
            this.value = (this.value.length <= 10 ? this.value : this.value.substring(0, 10));
        });
    });

Now just add the MultiLineLimitclass to any of your <asp:TextBox> textbox of TextMode="MultiLine".

<asp:TextBox ID="txtBodySMS" CssClass="MultiLineLimit" runat="server" Rows="10" TextMode="MultiLine" Width="100%"></asp:TextBox>

Remember in either scenario client side validation can be removed. If your storing this in a database it should always be validated server side as well.

clamchoda
  • 4,411
  • 2
  • 36
  • 74
  • 2
    But then when you reach the character limit - the textbox is frozen, you cant delete anything from it – DNKROZ Mar 16 '14 at 21:54
  • 3
    this works on keydowns, but using ctrl+v to paste a large amount of text into the box breaks this, and you can still enter as much as you like – Rich Oct 08 '14 at 10:43
  • @Rich You were both right I did not notice that over the years. I have fixed – clamchoda Mar 20 '19 at 18:25
19

This did it for me. I did not keep the MultiLine property.

<asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="2" Width="100%"></asp:TextBox>
TylerH
  • 20,799
  • 66
  • 75
  • 101
Beginner
  • 28,539
  • 63
  • 155
  • 235
13

Maximum character length Validation (Maximum 8 characters allowed)

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox1" ID="RegularExpressionValidator1" ValidationExpression = "^[\s\S]{0,8}$" runat="server" ErrorMessage="Maximum 8 characters allowed."></asp:RegularExpressionValidator>

Minimum character length Validation (Minimum 8 characters required)

<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox2" ID="RegularExpressionValidator2" ValidationExpression = "^[\s\S]{8,}$" runat="server" ErrorMessage="Minimum 8 characters required."></asp:RegularExpressionValidator>

Minimum and Maximum character length Validation (Minimum 5 and Maximum 8 characters required)

<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator Display = "Dynamic" ControlToValidate = "TextBox3" ID="RegularExpressionValidator3" ValidationExpression = "^[\s\S]{5,8}$" runat="server" ErrorMessage="Minimum 5 and Maximum 8 characters required."></asp:RegularExpressionValidator>
live-love
  • 48,840
  • 22
  • 240
  • 204
12

MaxLength="Int32"

<asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="220"                         
           TextMode="MultiLine" Width="100%"></asp:TextBox>
Senad Meškin
  • 13,597
  • 4
  • 37
  • 55
4

AFAIK maxlength has never worked in conjunction with the "multiline" mode. Therefore I would suggest some client-side js/jquery and server-side to get around the problem.

Mike
  • 2,912
  • 4
  • 31
  • 52
2

Just type below two line in .cs page load

textbox1.Attributes.Remove("MaxLength");
textbox1.Attributes.Add("MaxLength", "30");

Hope it will help !

Alok singh
  • 31
  • 3
  • Top voted answer does not work when user is copy/pasting into textbox. So a modified version of this answer (i.e. handling in javascript/jquery) works best. – Douglas Timms Mar 08 '19 at 21:25
1
<asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="220" 
    TextMode="MultiLine" Width="100%">
</asp:TextBox>
derloopkat
  • 6,232
  • 16
  • 38
  • 45
Zimi
  • 11
  • 1
0

It is important to note that using MaxLength alone (with no other properties to add, just like the other answers) works ONLY for projects in .NET Framework 4.5 and above.

I'm using 4.5, and it worked for my project

<asp:TextBox ID="txtSample" MaxLength="3" runat="server"/>

TextBox.MaxLength Property (MSDN Documentation)

ellekaie
  • 337
  • 1
  • 7
  • 21
0

Set the MaxLength attribute to the number of characters.

Tom Robinson
  • 8,348
  • 9
  • 58
  • 102
0

You are looking for MaxLength: Look here

Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
Theofanis Pantelides
  • 4,724
  • 7
  • 29
  • 49
0

Have you tried setting the MaxLength Property on the TextBox? for Reference

Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
Peter Mourfield
  • 1,885
  • 1
  • 19
  • 38
0

It seems to be a curious oversight in the design of ASP.NET (leaving aside the anomaly with textareas) that you can set the MaxLength property of a textbox but there seems to be no way provided to enforce this limit server-side without explicitly adding a validator. That's a nuisance if you have lots of fields and just want to be sure that no-one is subventing the limits of the form by injecting their own POST data. So I wrote this, which seems to do the trick - obviously you might not want to force Response.End

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        Dim colControls As Collection = New Collection
        getControlList(colControls, Me)
        For Each ctlNextPlease As Control In colControls
            If TypeOf (ctlNextPlease) Is TextBox Then
                Dim ctlTextBox As TextBox = ctlNextPlease
                If Len(Request(ctlTextBox.ID)) > ctlTextBox.MaxLength Then
                    Response.Write("The value <i>" & Request(ctlTextBox.ID) & "</i> submitted for <b>" & ctlTextBox.ID & "</b> exceeds the permitted maximum length (" & ctlTextBox.MaxLength & ") for that value")
                    Response.End()
                End If
            End If
        Next
...
End Sub

Public Shared Sub getControlList(ByRef colControls As Collection, ByVal rootControl As Control)
  colControls.Add(rootControl)
  If rootControl.Controls.Count > 0 Then
    For Each controlToSearch As Control In rootControl.Controls
      getControlList(colControls, controlToSearch)
    Next
  End If
End Sub
DJDave
  • 865
  • 1
  • 13
  • 28
0

Add an extender of type FliterTextBoxExtender for your text box
it should appear like that

<asp:TextBox ID="TxtCellular" runat="server"></asp:TextBox>
<asp:FilteredTextBoxExtender ID="TxtCellular_FilteredTextBoxExtender" 
                    runat="server" Enabled="True" TargetControlID="TxtCellular" FilterType="Numbers">
</asp:FilteredTextBoxExtender>
Mario S
  • 11,715
  • 24
  • 39
  • 47