Reputation: 10240
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" />
Upvotes: 1
Views: 271
Reputation: 5204
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;
});
});
Upvotes: 0
Reputation: 8706
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 (e.g. PHP).
HTML input maxlength
can be easily bypassed e.g with JavaScript.
Consider the following fiddle, that shows the problem: http://jsfiddle.net/2YUca/
Upvotes: 2