MaxLength属性不适用于MultiLine asp:textbox

时间:2014-11-26 05:15:03

标签: html asp.net

我尝试使用 MaxLength asp:textbox TextMode =" MultiLine" 中的特定字符数>财产。但它不起作用。有什么调整可以解决这个问题?

<asp:TextBox ID="txtComment" runat="server" Width="90%" class="form_txtnormal" TextMode="MultiLine" Rows="1" MaxLength="250"></asp:TextBox>

3 个答案:

答案 0 :(得分:2)

使用JavaScriptRegularExpression来验证长度。将TextBox设置为MultiLine TextBox后,最大长度无关紧要,因为它变为TextArea而不是inputbox

Here's一个例子

答案 1 :(得分:1)

当您处于Multiline TextMode时,MaxLength对该TextBox控件没有任何影响。因此,您可以使用客户端验证来检查每个 keypress 上的输入字符串长度,并限制您在输入超出最大长度时输入额外字符使用 event.preventDefault() 限制 keypress 事件的默认行为。 (您也可以使用其他答案中提到的正则表达式)

在头部分添加此脚本:

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
    $(document).ready(function () {
        $("#txtComment").on("keypress", function (e) {
            if ($(this).val().length == 250) {
                e.preventDefault();
            }
        });
    });
</script>

注意: 如果要将此验证脚本添加到多个控件,请使用相同的类名标记所有控件,并在脚本中用该类名替换控件的id所有控件。

参考文献: .keypress()event.preventDefault()

答案 2 :(得分:0)

解决了这个问题。

我的文本框是在Gridview中动态创建的,所以我在网格的Itembound事件中添加了这个属性。

protected void grdAreaOfEvaluation_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item.ItemIndex > -1)
    {
         TextBox txtComment = (TextBox)(e.Item.FindControl("txtComment"));
         txtComment.Attributes.Add("maxlength","250");
    }
}

如果您没有动态创建文本框,这也适用于页面加载事件。我没有检查过这个。

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
         txtComment.Attributes.Add("maxlength","250");
    }
}
相关问题