最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Restrict Textarea for not accepting 250 character - Stack Overflow

programmeradmin5浏览0评论

I have a textarea in C#, please see below code:

<asp:Label ID="lblQuestions" runat="server" CssClass="addinfo">
                    Question & Comments</asp:Label>
<asp:TextBox ID="txtQuestions" Rows="5" Columns="5" TextMode="MultiLine" runat="server" MaxLength="250"></asp:TextBox>

Now I want that textarea should not accept more than 250 characters, whatever user do COPY & PASTE, by WRITING and DRAG & DROP etc, if user try to copy or drag & drop more than 250 character the first 250 characters should be copied in textarea. I know that there no MAXLENGTH attribute in TEXTAREA. If it is not possible with .NET the solution with javascript or Jquery will work.

Please help

I have a textarea in C#, please see below code:

<asp:Label ID="lblQuestions" runat="server" CssClass="addinfo">
                    Question & Comments</asp:Label>
<asp:TextBox ID="txtQuestions" Rows="5" Columns="5" TextMode="MultiLine" runat="server" MaxLength="250"></asp:TextBox>

Now I want that textarea should not accept more than 250 characters, whatever user do COPY & PASTE, by WRITING and DRAG & DROP etc, if user try to copy or drag & drop more than 250 character the first 250 characters should be copied in textarea. I know that there no MAXLENGTH attribute in TEXTAREA. If it is not possible with .NET the solution with javascript or Jquery will work.

Please help

Share Improve this question edited Jul 15, 2009 at 12:11 Shimmy Weitzhandler 105k126 gold badges434 silver badges639 bronze badges asked Jun 19, 2009 at 6:49 Manoj SinghManoj Singh 7,70734 gold badges122 silver badges200 bronze badges 2
  • This seems to be a duplicate of this question stackoverflow./questions/1334286/… – Raúl Roa Commented Sep 8, 2009 at 19:43
  • Except that question's answer only works in IE - and is kinda ugly - and doesn't work with right click copy/paste or drag/drop. – gnarf Commented Sep 8, 2009 at 21:21
Add a ment  | 

7 Answers 7

Reset to default 3

You have to wire functions for the events

onpaste, onkeyup and onfocus of the area for which you want to do this action.

For an asp textbox I think you have to consider only OnTextChanged event.

For textarea

<INPUT id="counterMessage" readOnly size="3" value="250" name="counterMessage">                                                                                                     
<TEXTAREA onpaste="PasteCounter(this.form.txtAreaMessage,this.form.counterMessage,250);"
                                                                                                                            id="txtAreaMessage" onkeyup="textCounter(this.form.txtAreaMessage,this.form.counterMessage,250);"
                                                                                                                            style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; OVERFLOW: hidden; BORDER-LEFT: 0px; WIDTH: 99%; BORDER-BOTTOM: 0px; HEIGHT: 95px; TEXT-ALIGN: justify"
                                                                                                                            onfocus="textCounter(this.form.txtAreaMessage,this.form.counterMessage,250);" name="txtAreaMessage"
                                                                                                                            rows="3" runat="server"></TEXTAREA>


function PasteCounter(field, countfield, maxlimit)
        {
            var len;
            var txt = clipboardData.getData("Text");
            txt = field.value + txt
            len = parseInt(txt.length);
            if ( len >  maxlimit )
            {
                event.returnValue=false;
                txt = txt.substring(0, maxlimit);       
                field.value = txt;                  
                alert("Only " + maxlimit + " characters are allowed");
            }
            countfield.value = maxlimit - txt.length;
        }    
        function textCounter(field, countfield, maxlimit)
        {
            if (field.value.length > maxlimit )
            {      
                field.value = field.value.substring(0, maxlimit );
                alert("Only " + maxlimit + " characters are allowed");
            }
            countfield.value = maxlimit - field.value.length;
        }

The countfield textbox is for showing remaining characters.

You can use jQuery to bind to multiple events at once

$("#txtQuestions").bind("keyup change blur input paste", function() {
  // fire this off a few ms after the event happens
  setTimeout(
   (function(el){ // closure to store "this" as "el"
     return function() { if (el.value.length>250) el.value.length = 250; }
   })(this), 10);
});

There is a library (jQuery.charcounter) out there that will automatically add the characters remaining and what not to the DOM as well.

You can do this with an ASP.NET validator as well:

<asp:TextBox ID="MyTextBox" runat="server" TextMode="MultiLine" Rows="4" />
<asp:RegularExpressionValidator Display="Dynamic" ID="RegularExpressionValidator1" ControlToValidate="MyTextBox" Text="<p>A maxiumum of 250 characters is allowed.</p>"  runat="server" ValidationExpression="^(.|\s){0,250}$" />

1) A very simple way to handle this is to start with the onChange event:

<textarea id="yourTextArea" onchange="this.value.length = Math.min(this.value.length, 250)"></textarea>

The major drawback here is that the textarea will not update until the focus has left the textarea.

2) You should be able to adapt the above example to a form validation function that fires on the form's onSubmit event.

<script type="text/javascript">
    document.forms[0].onsubmit = function() { document.getElementById("yourTextArea").value.length = Math.min(this.value.length, 250); }
</script>

3) If you want to do this validation on the server side, you really just need to get the textarea's value and truncate it.

string validText = yourTextArea.Value.Substring(0, 250);

Expanding on @gnarf's answer:

<textarea class="max-length" cols="30" id="ment-box" maxlength="250" rows="10"></textarea></span>
<span id="ment-box-chars-left">250</span> characters left
<script type="text/javascript>
    function updateCharsLeft(id, maxChars, length) {
        $('#' + id + '-chars-left').html(maxChars - length);
    }

    $(document).ready(function() {
        $('.max-length').each(function() {
            updateCharsLeft($(this).attr('id'), $(this).attr('maxLength'), $(this).val().length);
        });

        $('.max-length').bind('keyup change blur input paste', function() {
            var maxChars = $(this).attr('maxLength');

            // fire this off a few ms after the event happens
            setTimeout((function(el) { // closure to store "this" as "el"
                return function() {
                    if (el.value.length > maxChars) {
                        el.value = el.value.substring(0, maxChars);
                    }
                    updateCharsLeft(el.id, maxChars, el.value.length);
                }
            })(this), 10);
        });
    });
</script>

This uses an attribute, to specify the maximum number of characters and updates a label displaying the number of characters left as well. The text area must be given the class max-length and the element that will display the number of characters left, must have the same id as the corresponding text area with -chars-left appended to it.

For interactive feedback, you should do the above in javascript, as wired controls will not react until it is posted back to the server (requiring a page reload). This can cause quite a bit of server load if you update character counts on every keystroke.

Below is a rough js implementation that will simply count the number of ASCII characters on every change. This will also work if the textarea is modified due to cut and pasting:

<script type="text/javascript">
function countWords() {
var text = document.getElementById("txtBox1").value;
if (text.length > 250) text = text.substr(0,250);
document.getElementById("txtBox1").value = text;
}
</script>

<textarea id="txtBox1" onkeyup="countWords();" >text here</textarea>
<asp:TextBox
    onkeypress="return value.length<=10;"
    onpaste="return (value.length+clipboardData.getData('Text').length)<=10"
    TextMode="MultiLine"
    runat="server"  
/>
发布评论

评论列表(0)

  1. 暂无评论