How To Validate A Checkbox Input Using Php?
Solution 1:
You're presently assigning with a single =
sign instead of comparing ==
with
if (($pick_up = Yes) && ($pick_up = No))
you need to change it to
if (($pick_up == "Yes") && ($pick_up == "No")){...}
while wrapping Yes
and No
inside quotes in order to be treated as a string.
Edit:
Your best bet is to use radio buttons, IMHO.
Using checkboxes while giving the user both Yes and No options shouldn't be used; it's confusing.
It should either be Yes
ORNo
and not and.
<inputtype="radio" name="pick_up" value="Yes" />Yes
<inputtype="radio" name="pick_up" value="No" />No
That is the most feasible solution.
Solution 2:
I don't know why you need a checkbox for this (this is what radio button's are supposed to do), but you can do it something like:
if(!isset($_POST['pick_up']) || count($_POST['pick_up']) > 1) {
echo'please select at least 1 choice';
} else {
echo$_POST['pick_up'][0];
}
Then make your checkbox names:
name="pick_up[]"
Or if you really need to have separate error messages. Do something like this:
$errors['pick_up_no'] = '';
if(!isset($_POST['pick_up'])) {
$errors['pick_up_no'] = "Please let us know your airport pick up requirement!";
} elseif(count($_POST['pick_up']) > 1) {
$errors['pick_up_no'] = "Can not select Yes and No together!"; // weird UX, should have prevented this with a radio button
}
if($errors['pick_up_no'] != '') {
echo$errors['pick_up_no'];
} else {
echo$_POST['pick_up'][0];
}
Solution 3:
It is impossible for $_POST['pick_up'] to be both yes and no at the same time since the name is pick_up and not pick_up[] <- pointing to multiple variables. So it will either be yes or no either way because one parameter will overwrite the other. You would have to use javascript to verify only one is checked before submit in that case.
Solution 4:
Use array of checkbox field elements;
<inputtype="checkbox" name="pick_up[]" />Yes
<inputtype="checkbox" name="pick_up[]" />No
then in your PHP script:
<?php$pick_ups=$_POST['pick_up'];
$first=isset($pick_ups[0]); //true/false of first checkbox status$second=isset($pick_ups[1]); //true/false of second checkbox status?>
Again, as you've already been told, you should use radio-buttons for this purpose! Take into account that $_POST does not send checkbox if it is not set (check with isset($_POST['name'])
Post a Comment for "How To Validate A Checkbox Input Using Php?"