Reputation: 5
I what to validate a field so it will throw an error if its value empty or the length is less than or equal to 10. But it only validates when its empty if the length is 1 or more it submits the value.
Need Help here to make it validate
if (empty($_POST["comment"]) && $_POST["comment"] <= 10) {
$comment_err = "Please send a message more than 10 characters";
}
else {
$comment = sanitize($_POST["comment"]);
}
Upvotes: 0
Views: 88
Reputation: 2595
You have two problems in your code:
empty($_POST["comment"]) || $_POST["comment"] <= 10
strlen()
function http://php.net/manual/en/function.strlen.phpso your final code will be:
if(empty($_POST["comment"]) || strlen($_POST["comment"]) <= 10){
$comment_err = "Please send a message more than 10 characters";
}
else{
$comment = sanitize($_POST["comment"]);
}
Upvotes: 1
Reputation: 41810
Just check the length. If it's greater than 10 length, then it's definitely not empty, so you don't need to check for that explicitly.
if(isset($_POST["comment"]) && strlen($_POST["comment"]) > 10){
isset
is just there to prevent an undefined index warning if that comment key doesn't exist.
(This reverses your if and else blocks, by the way, because it checks for good data instead of the error condition.)
This was partially answered in the comments, but Funk Forty Niner is such a generous soul that he gives away his wisdom for free with no expectation of fake internet points, all he asks for in return is some r e s p e c t when he comes home.
Upvotes: 1
Reputation: 1901
Your question is not clear and precise, but I think what you're looking for if :
So use OR
( || ) in your if statement, and strlen()
to get variable length (as outlined in comment by Funk Forty Niner):
if(empty($_POST["comment"]) || strlen($_POST["comment"]) <= 10){
$comment_err = "Please send a message more than 10 characters";
}
else{
$comment = sanitize($_POST["comment"]);
}
Upvotes: 1