【问题标题】:MaxLength property not working with MultiLine asp:textboxMaxLength 属性不适用于 MultiLine asp:textbox
【发布时间】:2015-01-24 08:22:51
【问题描述】:

我尝试使用 MaxLength 属性将用户输入限制为 asp:textbox TextMode="MultiLine" 中特定数量的字符。但它不起作用。有哪些调整可以解决这个问题?

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

【问题讨论】:

标签: html asp.net


【解决方案1】:

当您处于多行文本模式时,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】:

解决了这个问题。

我的文本框是在 Gridview 中动态创建的,所以我在 Grid 的 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");
    }
}

【讨论】:

    【解决方案3】:

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

    Here's一个例子

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 2011-12-22
      • 2016-11-29
      • 2016-06-20
      • 2012-07-30
      • 1970-01-01
      • 2011-03-05
      相关资源
      最近更新 更多