Reputation: 1350
I'm coding out a simple contact form, and the following code is giving me trouble:
if(!strlen($_POST['lastname']) > 0){
echo '<p class="message error">Please enter the parent\'s last name.</p>';
}
if(!strlen($_POST['comments']) > 5){
echo '<p class="message error">Please tell us a little more in the comments field.</p>';
}
Relevant form element:
<textarea name="comments" cols="60" rows="5"><?=(isset($_POST['comments']) ? $_POST['comments'] : '')?></textarea>
When I leave both fields blank, only the first error message (along with the others not shown) displays, whereas the one for the comments field does not.
The error checking even returns with an error if I submit the comments fields with less than 5 characters, as it should, but the error message does not print. In addition, I even echoed the strlen() of the comments field when I submitted with it blank and it prints out 0.
Can anyone see what the problem here is?
Upvotes: 0
Views: 100
Reputation: 330
Just to be clear, the problem here is that the ! applies to the return value from strlen only and not the entire comparison expression. The above if statements will always return false.
It could be rewritten like this to work:
if (!(strlen($_POST['lastname']) > 0)){ /* display error */ }
This is because the ! negates the result of the expression nested in parentheses and not the number returned by strlen.
Also, I would recommend not returning the POSTed value unaltered in the HTML source, that's just asking for trouble...
Upvotes: 1
Reputation: 921
If you want to validate the data whether it is entered you can use following options too
if(empty($_POST['name'])){
echo 'Enter Name';
}
or
if(trim($_POST['name'])==''){
echo 'Enter Name';
}
Upvotes: 1
Reputation: 19194
Missing parenthesis?
if(!(strlen($_POST['lastname']) > 0)) {
echo '<p class="message error">Please enter the parent\'s last name.</p>';
}
if(!(strlen($_POST['comments']) > 5)) {
echo '<p class="message error">Please tell us a little more in the comments field.</p>';
}
Upvotes: 3
Reputation: 522005
if (!strlen > 0)
first evaluates strlen
, which gives, say, 10. This is then negated by !
to false
. This is then compared to > 0
, which is false
, since false
will be cast to 0
and 0 > 0
is false
. The other way around, if the string is actually empty, the condition will be true
.
You either want if (!(strlen > 0))
or if (strlen <= 0)
.
Upvotes: 5