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
}
trim()
will remove leading/trailing whitespace, as per the docs: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:
* 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:Your best bet is to test the trimmed string against an empty one via identical-equality (which tests the type too):
The
empty(0)
issue is an edge case, but avoiding it will potentially save you from tearing your hair out.You can
trim
the posted input and see if itsempty
, if it is, display an error.More info on
trim()
can be found here: http://php.net/manual/en/function.trim.php