Character Limit in HTML

前端 未结 6 1155
悲&欢浪女
悲&欢浪女 2020-12-04 23:04

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

6条回答
  •  离开以前
    2020-12-04 23:45

    There are 2 main solutions:

    The pure HTML one:

    
    

    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.

提交回复
热议问题