Welcome Guest, Not a member yet? Register   Sign In
Validating multi-dimensional arrays for conditional fields
#1

[eluser]Unknown[/eluser]
Hi,

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:
Code:
<!-- do you have children radio button //-->
</fieldset>
    <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>
</fieldset>

&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:
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!




Theme © iAndrew 2016 - Forum software by © MyBB