问题描述
在使用TextBox时,发现了一个问题,就是设置该控件的MaxLength属性之后并没有作用,长度超出范围之后仍能够输入内容。
通过查找资料发现,可能是TextBox控件在TextMode=“MultiLine”时,MaxLength属性的限制就失去了作用。
代码如下:
<asp:TextBox ID="Name" runat="server" Width = "300px" onfocus="this.select()" MaxLength="50" >
</asp:TextBox>
解决办法
之后在属性窗口中找到TextMode属性,其值为SingleLine。后发现有一Wrap属性效果相仿,将其设置为False后,发现MaxLength属性可以起作用了,问题解决。
代码如下:
<asp:TextBox ID="Name" runat="server" Width = "300px" onfocus="this.select()" MaxLength="50" Wrap="False">
</asp:TextBox>
- 其他解决办法
- 1.使用 RequiredFieldValidator控件 和 RegularExpressionValidator对TextBox控件 进行限制。
其中 RequiredFieldValidator控件 作用是验证是否输入内容;RegularExpressionValidator对TextBox控件 作用是验证是否符合格式(需要用到正则表达式,代码中的正则表达式不够完善)。
这种办法只能够在用户输入完毕之后对TextBox的内容进行验证,不能直接对其输入长度进行限制。
代码如下:
<asp:TextBox ID="Name" runat="server" Width = "300px" onfocus="this.select()" MaxLength="50" Wrap="False">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat = "server" ControlToValidate = "Name" InitialValue = "" Text = "名称不能为空" ErrorMessage = "*" Font-Size = "13px" Width = "110px" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat = "server" ControlToValidate = "Name" ErrorMessage = "*" Text = "长度限制100字符(若长度无误,请删改标点符号)" Font-Size = "13px" ValidationExpression = "[a-zA-Z0-9_\.\u4e00-\u9fff`~!@#$%^&\*()-_=+\{\}\[\]\\\;\'\,\<\>\?\/\s\、]{1,100}" style = " position:relative; left:-115px;"></asp:RegularExpressionValidator>
- 2.添加一些客户端限制的JS代码。(未尝试此办法)
前台:
<script language="javascript">
function isOver(sText,len)
{
var intlen=sText.value.length;
if (intlen>len)
{
alert("The content length must Less than or Equal "+len);
sText.focus();
sText.select();
}
}
</script>
<asp:TextBox id="txtName" style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 104px" runat="server" TextMode="MultiLine" Height="112px" Width="271px"></asp:TextBox>
后台:
Public void Page_Load(object sender, System.EventArgs e)
{
this.txtName.Attributes.Add("onblur","isOver(this,1000);");
}