What is the best way to limit the amount of text that can be entered into a 'textarea'?

前端 未结 6 573
生来不讨喜
生来不讨喜 2021-01-19 05:50

What is the best way to limit the amount of text that a user can enter into a \'textarea\' field on a web page? The application in question is ASP .NET, but a platform agnos

相关标签:
6条回答
  • 2021-01-19 06:20
    function limit(element, max_chars)
    {
        if(element.value.length > max_chars)
            element.value = element.value.substr(0, max_chars);
    }
    

    As javascript, and...

    <textarea onkeyup="javascript:limit(this, 80)"></textarea>
    

    As XHTML. Replace 80 with your desired limit. This is how I do it anyway.

    Note that this will prevent the user from typing past the limit in the textbox, however the user could still bypass this using javascript of their own. To make sure, you must also check with your server side language.

    0 讨论(0)
  • 2021-01-19 06:21

    The most user-friendly idea seems to me a solution like the Twitter-one. Provide a visual indication that the user has crossed the maximum but don't limit him in typing.

    Whatever Javascript you use, you will still have to validate at the server end. Users with Javascript disabled will otherwise be able to circumvent your limit.

    0 讨论(0)
  • 2021-01-19 06:25

    jQuery also provides some options here. Options, options, and options.

    0 讨论(0)
  • 2021-01-19 06:27

    I use this, where the limit is a must. It also provides the user with the number of characters left.

    function CountLength(vControl)
        {
            var strValue = vControl.value;
            var vMax = 480;
            var vLeft = vMax - strValue.length;
            if (vLeft < 0)
            {
                vLeft = 0;
            }
            var vMessage = returnObjById('TextCounter');
            if (document.all)
            {
                vMessage.innerText = vLeft + ' characters remaining.';
            }
            else
            {   
                vMessage.textContent = vLeft + ' characters remaining.';
            }
            if (vLeft == 0)
            {
                vControl.value = vControl.value.substring(0, vMax);
            }
        }
    
    0 讨论(0)
  • 2021-01-19 06:30

    use a RegularExpressionValidator Control in ASP.Net to validate number of character along with with usual validation

    0 讨论(0)
  • 2021-01-19 06:34

    As Javache said, you'll still have to check server side. We've been using the jQuery validator plugin which has support for Max lengths amongst tones of other stuff...

    0 讨论(0)
提交回复
热议问题