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

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

         


        
13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 09:43

    MaxLength does not apply to ASP.NET to Textboxes with TextMode="MultiLine". An easy way to do this and keep your MultiLine mark up would be to add:

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

    with 10 being the limit. Like so:

    
    

     

    EDIT Option One (Server side) The above example has some issues pointed out over the years. The underlying problem is a multi-line textBox is rendered as a text-area and MaxLength is removed. We can also fix in the C# or VB asp.net code behind of the page by forcing the re-attachment of MaxLength instead of attaching onkeypress.

        protected void Page_Load(object sender, EventArgs e)
        {
            txtBodySMS.Attributes.Add("maxlength", "10");
        }
    

    EDIT Option Two (Client side): Here's a simple jquery solution. Include the following script in your head instead of attaching onkeypress or editing the server side code.

        $(document).ready(function () {
            $(".MultiLineLimit").on('change keydown paste input', function () {
                this.value = (this.value.length <= 10 ? this.value : this.value.substring(0, 10));
            });
        });
    

    Now just add the MultiLineLimitclass to any of your textbox of TextMode="MultiLine".

    
    

    Remember in either scenario client side validation can be removed. If your storing this in a database it should always be validated server side as well.

提交回复
热议问题