Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textarea character limit by Javascript & PHP

I use 2 methods to check that the user is not entering too many characters in a textarea:

1) (passive) PHP:

$textarea = $_POST['textarea'];
if (strlen($textarea)>300){$verify="bad";}

2) (active-whyle typing) Javascript:

function ismaxlength(obj)
{
   var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
   if (obj.getAttribute && obj.value.length>mlength)
   obj.value=obj.value.substring(0,mlength)
}

And the textarea itself is as follows (html):

<textarea name="textarea" id="textarea" cols="40" rows="5" style="border: 1px solid #480091; width:460px;" wrap="soft" maxlength="300" onpaste="return ismaxlength(this)" onkeyup="return ismaxlength(this)"></textarea>

Both methods work, except the PHP strlen() function seems to count returns (line breaks) differently than my Javascript function.

Does anyone know how to resolve this, so that they both count the same # characters, regardless of line breaks & spaces, etc.

Thanks a lot!

like image 576
RLJ Avatar asked Jan 01 '11 18:01

RLJ


1 Answers

You have to convert line breaks first. In JavaScript, a line break is a single newline character. When it is sent, there are two. You can normalize them:

$textarea = $_POST['textarea'];
$textarea = str_replace("\r\n", "\n", $textarea);
$textarea = str_replace("\r", "\n", $textarea);

And then you can count the length of the textarea.

like image 112
Thai Avatar answered Sep 21 '22 07:09

Thai