Reputation: 125
I have a field in a form for entering the number of masters titles won by a Tennis player. Some players have 0 titles. Even though my validation checks for an empty field I cannot enter 0. What changes do I need to make to allow 0 to be entered?
if (empty($_POST["masters"])) {
$has_errors = true;
$mastersErr = "Enter 0-10";
} else {
$masters = validate_input($_POST["masters"]);
}
Upvotes: 0
Views: 2765
Reputation: 16923
use if ($_POST["masters"] === '') {
to check for empty string
this is because
empty($variable)
returns true if $variable equals false, null, '' (empty string) or 0
you can't use $_POST['masters'] == ''
because in PHP statement 0 == ''
is true
you have to use ===
operator
please also mind $_POST['xxx'] === 0
will never work because values in $_POST
are strings
Anyway if you want user to put number between 0-10 I would suggest to do this check
if(is_numeric($var) && ($var >= 0) && ($var <= 10) && (intval($var) == $var))
{
// OK
}else
{
// not OK
}
This is because space character will pass $_POST["masters"] === ''
check.
In validation you should always create if
statements keeping in mind to check "is this value OK", not "is this value bad". For example if you want to validate email you dont' check "is value empty" "is value a number" "is value a float", you check "is value a email"|
is_numeric()
is good, because
is_numeric('')
is falseis_numeric(' ')
is falseis_numeric(0)
is truebut beware! because
is_numeric('0.1')
is also true......so you need another check:
(intval($var) == $var)
- this is how you make sure user entered integer (not float) number
PHP Manual:
Upvotes: 6