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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With