1

I want to avoid to validate the form if the user enters white spaces,
but actually entering spaces the form is still validate...

<?php
$name = ""; $email = ""; $comment = ""; $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["website"]) && !empty($_POST["comment"])){
        $name =    test_input($_POST["name"]);
        $email =   test_input($_POST["email"]);
        $website = test_input($_POST["website"]);
        $comment = test_input($_POST["comment"]);
        echo htmlspecialchars("".$name."".$email."".$website."".$comment."");

    }else{
        echo htmlspecialchars("fill all fields");
    }
}

function test_input($data){
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

What I am doing wrong?

2 Answers2

1

i think you should check if the data is empty after trim You can try below code

if ($_SERVER["REQUEST_METHOD"] == "POST"){
        $name =    test_input($_POST["name"]);
        $email =   test_input($_POST["email"]);
        $website = test_input($_POST["website"]);
        $comment = test_input($_POST["comment"]);

    if(!empty($name) && !empty($email) && !empty($website) && !empty($comment)){

        echo htmlspecialchars("".$name."".$email."".$website."".$comment."");

    }else{
        echo htmlspecialchars("fill all fields");
    }
}
manuyd
  • 201
  • 1
  • 8
0

for just spaces try

$str = '      ';
if (ctype_space($str)) {}

or

if(trim($str) == '') {} // check a blank string or it's a whitespace

arrange this according your requirement

for more Check if string is just white space?

Community
  • 1
  • 1
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44