PHP Prevent the submission of empty fields contain

2019-07-27 05:15发布

问题:

When using PHP how can I validate a simple text input to check if the field only contains space character, I want to prevent it from being possible to sign up to my website with a blank name consisting of just spaces and the same goes for other inputs such as comments? If I check if it is empty it just returns it as not empty as it considers a space as a character regardless.

For future reference the answer was to first trim my post data:

$variable = mysql_real_escape_string(stripslashes(trim($_POST['field'])));

Also sanitised it here and then as for validation, you can then just use empty():

if(empty($variable)) {
//do something
}

回答1:

You can trim the posted input and see if its empty, if it is, display an error.

if(empty(trim($_POST['comments'])))
{
    // Its empty so throw a validation error
    echo 'Input is empty!'; 
}
else
{
    // Input has some text and is not empty.. process accordingly.. 
}

More info on trim() can be found here: http://php.net/manual/en/function.trim.php



回答2:

trim() will remove leading/trailing whitespace, as per the docs:

Strip whitespace (or other characters) from the beginning and end of a string

As discussed already, empty() will return a boolean (and needs a variable argument pre-5.5), indicating whether the passed variable is "empty" or not.

However, this may lead to some peculiar behavior. Consider the following:

$value = "0";            // possibly a perfectly valid non-empty value *
var_dump(empty($value)); // bool(true) ... what?

* I could foresee this: "How many times have I been arrested for public indecency? Um, well 0... Invalid input!? How does it know!?"

PHP will evaluate a string of only "0" as 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)
  • $var; (a variable declared, but without a value)

Your best bet is to test the trimmed string against an empty one via identical-equality (which tests the type too):

if (trim($value) !== '') {
    // the string wasn't empty
    // after calling trim()
}

The empty(0) issue is an edge case, but avoiding it will potentially save you from tearing your hair out.