How to limit multiline textbox in asp.net

{0 Comments}

In most of time it has been seen that when you give privilege to enter many character approximately a range of 200 to 600 characters in a multiline textbox, then there is greater chance that your user will enter large chunks of character. Then let’s limit the characters in the multiline text box.  But here max length property doesn’t work. So you can limit this using a JavaScript.  Add following JavaScript to  your asp.net page.   

 Javascript |  copy code |? 
01
<script type="text/javascript">
02
        function checkTextAreaMaxLength(textBox,e, length)
03
            {
04
                var mLen = textBox["MaxLength"];
05
                if(null==mLen)
06
                mLen=length;
07
                var maxLength = parseInt(mLen);
08
                    if(!checkSpecialKeys(e))
09
                    {
10
                      if(textBox.value.length > maxLength&minus;1)
11
                        {
12
                         if(window.event)//IE
13
                            e.returnValue = false;
14
                        else//Firefox
15
                            e.preventDefault();
16
                        }
17
                    }   
18
            }
19
 
20
        function checkSpecialKeys(e)
21
            {
22
            if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
23
                return false;
24
                else
25
            return true;
26
            }
27
        </script>

Then call the same function on key down event of the text box

Which is 

 HTML |  copy code |? 
1
onkeyDown="checkTextAreaMaxLength(this,event,'20');"

Then change the limit to your desire number, here it is 20

Leave a Comment

Your email address will not be published.