Forum Moderators: coopster

Message Too Old, No Replies

PHP Validation

Checkbox query issue

         

woldie

11:39 am on Jun 28, 2004 (gmt 0)

10+ Year Member



Hi,

I'm having some trouble with validation when it comes to using checkboxes.

Essentially what I have is a form with six checkboxes and one checkbox if they do not doing any of the above.

Firstly what I am trying to achieve is that if they do not select any of the checkboxes, then it throws back an error.

But if they select any of the 6 checkboxes or more than 1 then the form validates, but if they select any of 6 checkboxes and none of the above checkbox then it should throw an error.

Hope this makes sense?

Some code:

option 1
<input type="checkbox" name="option 1" value="">

option 2
<input type="checkbox" name="option 2" value="">

option 3
<input type="checkbox" name="option 3" value="">

option 4
<input type="checkbox" name="option 4" value="">

option 5
<input type="checkbox" name="option 5" value="">

option 1
<input type="checkbox" name="option 6" value="">

No strategy
<input type="checkbox" name="no_strat" value="">

Thanks in advance.

Woldie.

Warboss Alex

1:45 pm on Jun 28, 2004 (gmt 0)

10+ Year Member



Make the six checkbox elements an array, i.e.

option 1<input type="checkbox" name="check[]" value="1">
option 2<input type="checkbox" name="check[]" value="2">
option 3<input type="checkbox" name="check[]" value="3">
... etc ...

Then your 'none of the above' checkbox:
<input type="checkbox" name="none">

Then, in your $_POST validation, do something like the following:

if (( (is_array($_POST['check']) && (!isset($_POST['none'])) ) ¦¦ ( (!(is_array($_POST['check']))) && (isset($_POST['none'])) ) )
echo "is okay";

else throw_error();

Remember that $_POST checkbox variables are set if they've been checked, so we only need check that. If the 'check' set is an array (even one element would make it an array, since all the 'check' boxes are linked to an array (check[])) and the 'none' checkbox isn't set (which mean it hasn't been clicked), or the other way about, i.e. no check[] array and the 'none' has been set (checked) it should validate fine, otherwise throw an error you specify.

I think that's what you want to do. I haven't tested the code, so there might be the odd parentheses out of place .. ;)

Hope it helps,

Alex ...

woldie

2:07 pm on Jun 28, 2004 (gmt 0)

10+ Year Member



Thanks Warboss Alex,

I was actually thinking of using an array, but I wasn't quite sure obviously how to implement it, anyhow I'll give that a go.

Many thanks for your help

Woldie :o)