Jump to content

impose textarea character limit


RLJ

Recommended Posts

Hi, I use 2 methods to check that the user is not entering too many characters in a <html> textarea:

 

1) (passive) PHP:

$textarea = nl2br($_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!

Link to comment
https://forums.phpfreaks.com/topic/223040-impose-textarea-character-limit/
Share on other sites

That because you are using nl2br() BEFORE you count the characters. So, the PHP validation is converting a new line character to "<br />" (which is 6 characters) then you are checking the length. Check the length THEN convert the new lines to BR tags.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.