PDA

View Full Version : how to get error for too many characters in textarea


llizard
10-28-2005, 06:18 AM
I have set a limit of 300 characters for a textarea in a form. I'm trying to echo an error message if someone puts too many characters into the textarea. Knowing not all that much about php or programming, I have been trying unsuccessfully to use strlen

$comment = substr(trim($_POST['comment']), 0, 300);
$fixcomment = htmlentities($comment, ENT_QUOTES);

// require comment
if (($comment == "") || (strlen($comment) < 1) || (strlen($comment) > 300))
{
echo '<p class="error">Your <i>Brief</i> Message (required) - use <big>ctrl + &larr;</big> to go back to edit your message:<br /> <textarea name="comment" id="comment"></textarea></p>';
}
else {
echo '<p>Your Brief Message:<br />
<textarea name="comment" id="comment">' , $fixcomment , '</textarea></p>';
}

I've also tried
if (($comment == "") || (strlen($comment) > 300))

and
if ((strlen($comment) < 1) || (strlen($comment) > 300))

and
if ((strlen($comment) < 0) || (strlen($comment) > 300))

with the same lack of success. If more than 300 characters are typed into the textarea, the form processes and cuts off the message without throwing an error.

Any ideas on where I have made the mistake(s)?

I hope my question made sense.

Pennimus
10-28-2005, 09:19 AM
From the php manual -


<?php

function check_input($input, $maxlenght= 300)
$temp_array = explode(" ", $input);
foreach ($temp_array as $word) {
if (strlen($word) > $maxlenght) {
return false;
}
}
return true;
}
?>

llizard
10-28-2005, 03:23 PM
From the php manual -

Thank you for your reply, Pennimus. Yes, I should have mentioned that I stared at that strlen page in the PHP manual but do not understand enough about PHP to know where or how to implement it. (If I had understood it, I wouldn't have asked my question here.)

This is my attempt - that naturally didn't work:


$comment = substr(trim($_POST['comment']), 0, 300);
$fixcomment = htmlentities($comment, ENT_QUOTES);

function check_input($input, $maxlength=300)
{
$temp_array = explode(" ", $input);
foreach ($temp_array as $comment) {
if (strlen($comment) > $maxlength) {
return false;
}
}
return true;
}

// require comment
if (($comment == "") || (!check_input($_POST['comment'])))
{
echo '<p class="error">Your <i>Brief</i> Message (required) - use <big>ctrl + &larr;</big> to go back to edit your message:<br /> <textarea name="comment" id="comment"></textarea></p>';
}
else {
echo '<p>Your Brief Message:<br /><textarea name="comment" id="comment">' , $fixcomment , '</textarea></p>';
}

If the message is too long, the form returns with the truncated message rather than throwing an error