CodeIgniter Forums
Validating multi-dimensional arrays for conditional fields - Printable Version

+- CodeIgniter Forums (
+-- Forum: Archived Discussions (
+--- Forum: Archived Development & Programming (
+--- Thread: Validating multi-dimensional arrays for conditional fields (/thread-20106.html)

Validating multi-dimensional arrays for conditional fields - El Forum - 06-28-2009


I know this has been discussed a lot in the forums but I still can't get my head around validation of multi-dimensional arrays. Can someone help with this?

I am collecting information about people's children. So if they have children then they need to enter each child name and date of birth (for at least one child).

Here is an example of the form being generated:
<!-- do you have children radio button //-->
    <legend>Do you have children?</legend>
    &lt;input id="children_no" name="children" value="No" type="radio"&gt;&lt;label>No</label>
    &lt;input id="children_yes" name="children" value="Yes" checked="checked" type="radio"&gt;&lt;label>Yes</label>

&lt;!-- // fill in name and date of birth for each child if children=yes //--&gt;
<label for="childName1">Child 1 name </label>
    &lt;input name="child[1][name]" id="childName1" value="" type="text"&gt;
    <label for="childDob1">dob </label>
    &lt;input name="child[1][dob]" id="childDob1" value="" type="text"&gt;

<label for="childName2">Child 2 name </label>
    &lt;input name="child[2][name]" id="childName2" value="" type="text"&gt;
    <label for="childDob2">dob </label>
    &lt;input name="child[2][dob]" id="childDob2" value="" type="text"&gt;

I tried this validation code:
// If YES selected, then validate the array of children submitted
if ($this->input->post('children') == "Yes") {
    $i = 1;
    if (count($this->input->post('child')) > 1) {
        foreach ($this->input->post('child') as $childdetail) {
            $val_rules[] = array(
                'field'   => 'child['.$i.'][name]',
                'label'   => 'Child '.($i+1).' name',
                'rules'   => 'required'
            $val_rules[] = array(
                'field'   => 'child['.$i.'][dob]',
                'label'   => 'Child '.($i+1).' date of birth',
                'rules'   => 'required|callback_child_date_check['.$childdetail[dob].']'
            $i ++;

I have a function called "child_date_check" to use as a callback on the date values.

Thanks in advance!