Search code examples
htmlcharacter-limit

Character Limit in HTML


How do you impose a character limit on a text input in HTML?


Solution

  • There are 2 main solutions:

    The pure HTML one:

    <input type="text" id="Textbox" name="Textbox" maxlength="10" />
    

    The JavaScript one (attach it to a onKey Event):

    function limitText(limitField, limitNum) {
        if (limitField.value.length > limitNum) {
            limitField.value = limitField.value.substring(0, limitNum);
        } 
    }
    

    But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.