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'));
});

jsFiddle.

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.

Answer by Starx

Check this helpful tutorial from Matt.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!