tegah
tegah

Reputation: 5

How to make a field validate if it's not empty

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

Answers (3)

olibiaz
olibiaz

Reputation: 2595

You have two problems in your code:

  1. first your condition is not correct, you cannot have at the same time an empty index and checking his size. So you should have empty($_POST["comment"]) || $_POST["comment"] <= 10
  2. you also cannot check the length of a string by checking the value against an integer, as @Funk Forty Niner told in comments, you have to use strlen() function http://php.net/manual/en/function.strlen.php

so 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

Don&#39;t Panic
Don&#39;t Panic

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

Andr&#233; DS
Andr&#233; DS

Reputation: 1901

Your question is not clear and precise, but I think what you're looking for if :

  • Throw an error if variable is empty
  • Throw an error if variable length is less than 10

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

Related Questions