如何指定输入元素中允许的最大字符数 - 设置 maxlength 属性是否足够


How to specify a maximum number of characters allowed in an input element - Is setting a maxlength attribute enough?

我需要设置输入元素中允许的最大字符数。使用 maxlength 属性是否足够,还是我需要进一步的 PHP 或 JavaScript 验证?

这是我到目前为止所拥有的:

<input type="text" name="field-1" maxlength="20" />

对于客户端:是的,正如规范所说:

当 type 属性具有值"文本"或"密码"时,此属性指定用户可以输入的最大字符数。

虽然,正如@RobG提到的,您必须在服务器端验证数据(例如.PHP)。

HTML输入maxlength可以很容易地绕过,例如使用JavaScript。
考虑以下小提琴,它显示了问题:http://jsfiddle.net/2YUca/

在 Internet Explorer 9> 中,maxlenght 不适用于<textarea>字段。 要使其正常工作,您需要添加一些JS。 此示例使用jQuery,但您可以使用标准JS轻松完成此操作。

$(document).ready(function () {

$('textarea').on('keyup', function () {
    // Store the maxlength and value of the field.
    if (!maxlength) {
        var maxlength = $(this).attr('maxlength');
    }
    var val = $(this).val();
    var vallength = val.length;
    // alert
    if (vallength >= maxlength) {

        alert('Please limit your response to ' + maxlength + ' characters');
        $(this).blur();
    }

    // Trim the field if it has content over the maxlength.
    if (vallength > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});
//remove maxlength on blur so that we can reset it later.
$('textarea').on('blur', function () {
    delete maxlength;
});

});

使用

php 你可以使用 strlen() functio