Identification of form and codeigniter array as field names

I have a set of checkboxes in my HTML that look like this:

div class="grid_7"> <fieldset class="age shadow_50"> <label class="legend">Age Group</label> <div class="formRow checkbox"> <input id="" type="checkbox" name="age[]" value="child" /> <label>Child</label> </div> <div class="formRow checkbox"> <input id="" type="checkbox" name="age[]" value="30's" /> <label>30s</label> </div> <div class="formRow checkbox"> <input id="" type="checkbox" name="age[]" value="60's" /> <label>60's</label> </div> <div class="formRow checkbox"> <input id="" type="checkbox" name="age[]" value="teen" /> <label>Teen</label> </div> <div class="formRow checkbox"> <input id="" type="checkbox" name="age[]" value="40's" /> <label>40's</label> </div> <div class="formRow checkbox"> <input id="" type="checkbox" name="age[]" value="70's" /> <label>70's</label> </div> <div class="formRow checkbox"> <input id="" type="checkbox" name="age[]" value="20's" /> <label>20's</label> </div> <div class="formRow checkbox"> <input id="" type="checkbox" name="age[]" value="50's" /> <label>50's</label> </div> </fieldset> </div> 

I set a check rule in my controller, which (in my opinion) ensures that the checkbox is checked,

 $this->form_validation->set_rules('age[]', 'age group', 'required|trim'); 

When testing this, however, I get an error message forever with the name age []. I just want to check that age [] is not empty.

How can i achieve this?

+4
source share
2 answers

You cannot test age[] in this way, it is an array. There are several ways to do this, but what you did required is not one of them.

You can use javascript or run the age[] value through your own callback function - this is one of the methods.

Details for using arrays in CI are here:
https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#arraysasfields

If you make this a javascript route, you can use jQuery to iterate through your checkboxes (use the class to connect them) and just make sure one of them is checked.

+1
source

An old question, but for those who are struggling to do this, I believe that you can do this by setting the rule to age , not age[] , i.e.

 $this->form_validation->set_rules('age', 'age group', 'fnName'); 
0
source

All Articles