简体   繁体   中英

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?

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.

Although, as @RobG mentioned, you have to validate data on server-side (eg PHP).

HTML input maxlength can be easily bypassed eg with JavaScript.
Consider the following fiddle, that shows the problem: http://jsfiddle.net/2YUca/

In internet explorer 9 > maxlenght does not work for <textarea> fields. 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

$(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()函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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