简体   繁体   English

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

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

I need to set the maximum number of characters allowed in an input element. 我需要设置输入元素中允许的最大字符数。 Is using the maxlength attribute enough or do I need some further PHP or JavaScript validation? 使用maxlength属性是否足够?还是需要进一步的PHP或JavaScript验证?

This is what I have so far: 这是我到目前为止的内容:

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

For client-side: yes, as specification says: 对于客户端:是的,如规范所述

When the type attribute has the value "text" or "password", this attribute specifies the maximum number of characters the user may enter. 当type属性的值为“ text”或“ password”时,此属性指定用户可以输入的最大字符数。

Although, as @RobG mentioned, you have to validate data on server-side (eg PHP). 尽管,如@RobG所述,您必须在服务器端(例如PHP)上验证数据。

HTML input maxlength can be easily bypassed eg with JavaScript. HTML输入的maxlength 可以很容易地绕过,例如使用JavaScript。
Consider the following fiddle, that shows the problem: http://jsfiddle.net/2YUca/ 考虑下面的小提琴,它显示了问题: http : //jsfiddle.net/2YUca/

In internet explorer 9 > maxlenght does not work for <textarea> fields. 在Internet Explorer 9中,maxlenght不适用于<textarea>字段。 To get this to work you'll need to add some JS This example uses jQuery, but you could do it just as easily with standard JS 要使其正常工作,您需要添加一些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()函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM