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

时间:2013-11-14 22:58:58

标签: javascript php jquery html forms

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

这是我到目前为止所做的:

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

3 个答案:

答案 0 :(得分:2)

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

  

当type属性的值为“text”或“password”时,此属性指定用户可以输入的最大字符数。

尽管如@RobG所述,您必须验证服务器端的数据(例如PHP)。

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

答案 1 :(得分:0)

在Internet Explorer 9中&gt; 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;
});

});

答案 2 :(得分:0)

使用php你可以使用strlen()函数