March 16, 2011
Limiting Html Textarea
Question by Roland
I’m having a textarea
<textarea name="Users[address]" id="Users_address"></textarea>
Now I do not want the user the enter more than 25 characters per line and not more than 3 lines, is this possible to validate and achieve and how? The validation can be done in javascript or php
Answer by alex
jQuery
As the user types, this will remove text which doesn’t match the rules.
var maxLines = 2,
maxLineWidth = 5;
$('#Users_address').bind('change keyup paste drop', function() {
var value = $(this).val(),
lines = value.split('n'),
linesLength = lines.length;
if (linesLength > maxLines) {
lines = lines.slice(0, maxLines);
linesLength = maxLines;
}
for (var i = 0; i < linesLength; i++) {
if (lines[i].length > maxLineWidth) {
lines[i] = lines[i].substring(0, maxLineWidth);
}
}
$(this).val(lines.join('n'));
});
PHP
Where $str
is your user inputted string.
define('MAX_LINES', 10);
define('MAX_LINE_LENGTH', 25);
$lines = explode("n", $str);
if (count($lines) > MAX_LINES) {
echo 'Too many lines.';
}
foreach($lines as $line) {
if (strlen($line) > MAX_LINE_LENGTH) {
echo 'Too many chars wide';
break;
}
}
This will reject text which doesn’t match the rules. To turn any text into text that follows the rules (possibly dropping characters), just convert the jQuery above to PHP.