-1

I am trying to make a PHP form and check that text boxes are empty. My code:

<form method="post"> 
  Name: <input type="text" name="name">
  <span class="error">* <?php echo $nameErr;?></span>

//check user that fill in blank
if (empty($_POST["name"])) {
   $nameErr = "Name is required";
   }

Is this an effective way to check that the user filled in the blank? If user type "0", the system shows an error message.

Does anyone have a more efficient way?

tommy
  • 99
  • 1
  • 2
  • 9

3 Answers3

0

The problem is that the following values are considered to be "empty()":

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)

As such, when validating that a variable actually contains data, you'll also want to check isset() in addition to empty():

if (empty($_POST["name"]) || !isset($_POST["name"])) {
  $nameErr = "Name is required";
}

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

You could use trim(), which deletes whitespace at the beginning or end, so it will also delete a single whitespace

if (empty(trim($_POST["name"]))) {
  $nameErr = "Name is required";
}

or (to avoid the "0" problem)

if (trim($_POST["name"]) !== "") {
  $nameErr = "Name is required";
}
Johannes
  • 64,305
  • 18
  • 73
  • 130
0

If user type "0", the system shows an error message

Make use of filter_var(), and more precisely FILTER_VALIDATE_INT.

See the comments inside:

$input = 0; // is an integer and will not echo

if(filter_var($input, FILTER_VALIDATE_INT) === false){
  echo "The input is not an integer";
}

$input = "0"; // is an integer and will not echo

if(filter_var($input, FILTER_VALIDATE_INT) === false){
  echo "The input is not an integer";
}

$input = "text"; // is NOT an integer and will echo

if(filter_var($input, FILTER_VALIDATE_INT) === false){
  echo "The input is not an integer";
}

$input = "text123"; // is NOT an integer and will echo

if(filter_var($input, FILTER_VALIDATE_INT) === false){
  echo "The input is not an integer";
}

As for your:

Is this an effective way to check that the user filled in the blank?

  • empty() does work well here, as isset() is more effective with radio/checkboxes.

Have a look at the following and the differences between both:

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141