How to limit the number of characters allowed in a textbox?

前端 未结 13 923
一整个雨季
一整个雨季 2020-12-17 09:19



        
相关标签:
13条回答
  • 2020-12-17 09:22

    MaxLength="Int32"

    <asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="220"                         
               TextMode="MultiLine" Width="100%"></asp:TextBox>
    
    0 讨论(0)
  • 2020-12-17 09:30
    <asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="220" 
        TextMode="MultiLine" Width="100%">
    </asp:TextBox>
    
    0 讨论(0)
  • 2020-12-17 09:31

    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.

    0 讨论(0)
  • 2020-12-17 09:31

    Set the MaxLength attribute to the number of characters.

    0 讨论(0)
  • 2020-12-17 09:31

    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
    
    0 讨论(0)
  • 2020-12-17 09:33

    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)

    0 讨论(0)
提交回复
热议问题