Forum Moderators: coopster

Message Too Old, No Replies

Checkbox validation if no checkboxes are checked

         

ratman7

5:12 pm on Nov 2, 2007 (gmt 0)

10+ Year Member



Basic PHP question here: I would like to validate the checkbox field with php to make sure that at least one box is checked. When the form is submitted, the form results print the values of the the boxes checked. However, if the user did not check any of the boxes, I want to have the form results say "You did not check any boxes".

I know this should be simple, but I'm having trouble with it. Any help would be appreciated.

// importance is the name of the checkboxes

<?php

for ($x = 0; $x < count($importance); $x++)

echo "<p>$importance[$x]</p>"; // prints checked values

?>

cameraman

5:26 pm on Nov 2, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Use the isset() [php.net] function to check for it.
If you have a checkbox:
<form method="post"....
<input type="checkbox" name="check" value="1">

if it's been checked, you'll get
$_POST['check']=1

but if it's not checked, it won't appear in the post array, so
if(!isset($_POST['check']))
echo "The checkbox isn't checked";

ratman7

10:32 pm on Nov 2, 2007 (gmt 0)

10+ Year Member



but if it's not checked, it won't appear in the post array, so
if(!isset($_POST['check']))
echo "The checkbox isn't checked";

Thanks for your response, but I tried that. Problem is, the "Checkbox isn't checked" appears on the page when the page loads, BEFORE the form is submitted. I want it to appear after the form is submitted, if and only if there were not checkboxes selected.

cameraman

12:25 am on Nov 3, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you're using the same script to both display and process the form, you would put that test in the processing section. If you're using a submit button with a name of "Submit", you could do something like this:

if(isset($_POST['Submit'])) {
if(!isset($_POST['check'])) {
echo "The checkbox isn't checked";
} // EndIf no checkboxes checked
} // EndIf the form has been submitted

ratman7

6:52 am on Nov 3, 2007 (gmt 0)

10+ Year Member



Ok, I will ponder that and report back. Thanks!

ratman7

7:36 pm on Nov 5, 2007 (gmt 0)

10+ Year Member



I ended up going with this, which is a simple and common solution:

Hidden checkbox field in the html:

<input type="hidden" name="checkbox[]" value="0" />

And the php:

elseif ($type == "0") { // hidden checkbox value

echo "No checkboxes were checked";

}

Since the $_POST array for the checkboxes only gets populated with values of boxes that are checked, PHP uses the only value provided, which is "0".