Validating multidimensional arrays in Code Igniter

2019-06-25 04:37发布

问题:

I'm having a weird problem with the form_validation module of code igniter. I'm trying to validate multi dimensional arrays from the form post, but its not working as expected. I've used this a hundred times (exaggeration) with standard form posts so I'm familiar with it.

My form post looks like this

Array
(
    [location_edit_id] =>
    [theImage] => 
    [thePDF] => 
    [loc] => Array
    (
        [name] => 
        [content_1] => 
        [content_2] => 
        [opening_hours] => 
        [seats] =>
    )
    [ad] => Array
    (
        [address_1] => 
        [address_2] => 
        [address_3] => 
        [town_city] => 
        [county_id] =>
        [region_id] =>
        [postcode] => 
        [telephone] => 
        [email] => 
    )
 )

According to the docs - the action in my controller needs to look like this if I want to validate the $_POST['loc']['name']

$this->validation->set_rules( 'loc[name]', 'Location Name', 'required');

if ($this->validation->run() == FALSE)
{
    die( "did not validate" );
} 
else
{
    die( "validated" );
}

no matter what I do, this always validates even if $_POST['loc']['name'] is empty. I've examined the library file libraries/Validation.php and I cant see anywhere where this would actually work (as its always just looking for variable name matches - not arrays), so I'm not sure whats going on.

EDIT: I'm using Code igniter version 1.7.2 which is the latest stable release.

回答1:

It looks like you're using the wrong library. The Validation library is deprecated. Try using Form_validation (libraries/form_validation.php) instead.

$this->load->library('form_validation');

$this->form_validation->set_rules( 'loc[name]', 'Location Name', 'required');

if ($this->form_validation->run() == FALSE)
{
    die( "did not validate" );
}
else
{
    die( "validated" );
}


回答2:

i am not sure about the latest CI versions but back in 1.6 days this wasn't possible .. what version of CI are u using?

I used to use this back then

http://codeigniter.com/wiki/Assosiative_Arrays_via_POST/