Welcome Guest, Not a member yet? Register   Sign In
Checking for a checked box in a group of checkboxes.
#1

[eluser]NBrepresent[/eluser]
It's a tongue-twister.

Also, it's an annoyance. I really need to make a custom callback for the validation class, for a situation where at least one MUST be checked, and multiple boxes checked is OK.

This is what I've got so far... It isn't working:

Code:
function checkbox_check() {
        if ($this->input->post('a')==FALSE && $this->input->post('b')==FALSE) {
            $this->validation->set_message('checkbox_check','Either a or b must be checked.');
            return FALSE;
        } else {
            return TRUE;
        }

So how do you do this? Also, I can foresee needing to limit the number of boxes checked (at least 1, no more than say, 4). Baby steps...
#2

[eluser]xwero[/eluser]
First some tips:

I see you are using 2 different names for your checkboxes. If it's a group you better choose one name with square brackets at the end. This will post your checkbox values in an array.
Another thing is see is that you are using == instead of === which is required to compare a boolean. If you want to know if a boolean is false you can also use the alternative
Code:
!$this->input->post('a')
If you are only have two values i think you better use a radiobutton group and use the required rule.

My proposal:

Instead of using callbacks you can extend the validation rules by creating a MY_Validation class, an example you can find here.

The max_count, min_count and exact_count methods are just what you are looking for. The methods have to be used with the required method of the CI library to check if at least one checkbox of the group is checked.

The code:
Code:
// view
<p>Do you love CodeIgniter<br>
&lt;input type="checkbox" name="group[]" value="1"&gt; Yes<br>
&lt;input type="checkbox" name="group[]" value="1"&gt; No</p>
//controller
$rules['group'] = 'required|exact_count[1]';

So far my mini tutorial Smile
#3

[eluser]NBrepresent[/eluser]
Thanks for the reply, xwero. I did see that there were some extensions to the Validation library posted to the wiki, but I didn't know for sure that they would do what I needed.

I'll try it using the checkbox values in an array, I did try that once before somewhere along the way but I still couldn't get the validation working, so I tried the 'one checkbox, one name' approach.

Good tips, thanks!




Theme © iAndrew 2016 - Forum software by © MyBB