2011-05-24 83 views
17
<asp:TextBox ID="txtBodySMS" runat="server" Rows="10"       
      TextMode="MultiLine" Width="100%"></asp:TextBox> 

這是我的文本框。我如何限制用戶可以在其中鍵入的字符數?asp文本框限制字符數?

回答

13
<asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="2" 
            Width="100%"></asp:TextBox> 
10

的MaxLength = 「的Int32」

<asp:TextBox ID="txtBodySMS" runat="server" Rows="10" MaxLength="220"       
      TextMode="MultiLine" Width="100%"></asp:TextBox> 
+0

不起作用,他們仍然能夠進入超過220個字符 – Beginner 2011-05-24 14:06:45

+0

那麼什麼是錯的,這是微軟證明財產 – 2011-05-24 14:10:25

+5

不是,需要拿出多 – Beginner 2011-05-24 14:12:58

0

設置maxlength屬性的字符的數目。

+1

行不通的嘗試 – Beginner 2011-05-24 14:09:41

0

您正在尋找的MaxLength:看here

0

您是否嘗試過在文本框設置MaxLength屬性?對於Reference

+0

是它似乎不工作 – Beginner 2011-05-24 14:08:49

2

AFAIK maxlength從來沒有與「多行」模式一起使用。因此,我會建議一些客戶端js/jquery和服務器端來解決這個問題。

0

添加型FliterTextBoxExtender的擴展您的文本框中
它應該出現這樣的

<asp:TextBox ID="TxtCellular" runat="server"></asp:TextBox> 
<asp:FilteredTextBoxExtender ID="TxtCellular_FilteredTextBoxExtender" 
        runat="server" Enabled="True" TargetControlID="TxtCellular" FilterType="Numbers"> 
</asp:FilteredTextBoxExtender> 
16

MaxLength並不適用於TextMode="MultiLine"。一個簡單的方法來做到這一點並保持你的MultiLine馬克了將補充:

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

10爲限。像這樣:

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

但是,當你達到字符數限制 - 文本框被凍結,你不能刪除它的任何東西 – DNKROZ 2014-03-16 21:54:25

+2

這可以在keydowns上運行,但使用ctrl + v將大量文本粘貼到框中可以打破這一點,並且仍然可以輸入儘可能多的你 – Rich 2014-10-08 10:43:41

6

最大字符長度驗證(允許的最大8個字符)

<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> 

最小字符長度驗證(最少8個字符需要)

<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> 

最小和最大字符長度驗證(需要最少5個字符和最多8個字符)

<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> 
+0

這不適用於0個字符。 – 2017-04-11 09:41:02

0

單獨使用MaxLength(沒有其他屬性可以添加,就像其他答案一樣)僅適用於.NET Framework 4.5及更高版本中的項目,這一點很重要。

我使用的是4.5,它的工作爲我的項目

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

TextBox.MaxLength Property (MSDN Documentation)

-1

中的.cs頁面加載

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

希望這將有助於正下方兩條線型!