Khaled
Khaled

Reputation: 690

Code igniter Form Validation with All Fields Posted as an Array

I'm facing a problem regarding general form validation in codeigniter. In my case, the fields are posted in array $m_data = json_decode($this->input->post('data')); and needs to be validated before sending them to the model. see this example

        $m_data = json_decode($this->input->post('data'));          
        $validation_rules = array(
             $m_data['title']   => 'trim|xss_clean|required|max_length[50]',
             $m_data['code']    => 'trim|xss_clean|required|max_length[50]'
        );
        foreach ($validation_rules as $key => $value){
            $this->form_validation->set_rules($key,$key,$value);
        }


        if ($this->form_validation->run()) {
            foreach ($validation_rules as $key => $value){          
                $m_data[$key] = $this->form_validation->set_value($key);
            }
            // do insertion
        }

the problem here that form validation will take each field separately as posted data using the 'key' of value posted and run the rules over it. I tried to create custom validation that receive an array of fields as input but I had no clue how to do this.

can you help me figuring a way to validate the array content using CI form validation, any input is appreciated

Upvotes: 4

Views: 6795

Answers (2)

Khaled
Khaled

Reputation: 690

Hopefully, I found the answer to this that really works, but I think it's just temporary answer so don't depend on it, but it works.

        $validation_rules = $this->config->item('class');
        foreach ($validation_rules as $row){
            $_POST[$row['field']] = $m_data->$row['field'];         
        }

what I did here is to set the $_POST['name_of_fields_in_the_array'] by the value posted from the view which is $m_data, and that made the validation works very well

Upvotes: 1

Nick Pyett
Nick Pyett

Reputation: 3408

You can use arrays as field names with CI form validation.

http://codeigniter.com/user_guide/libraries/form_validation.html#arraysasfields

What you would need to do is something like this.

$this->form_validation->set_rules('data[]', 'Data', 'trim|xss_clean|required|max_length[50]');

if ($this->form_validation->run()) {
// DO INSERT
}
else
{
// LOAD VIEWS
}

I'm pretty sure the rules are applied recursively through your data, but I'd do some tests to make sure. I tried it with different field types (see HTML below) and it was working for the required rule at least. (This is just quick HTML, I'd use the CI form helper).

<input type="radio" value="Test data" name="data[]" />
<input type="radio" value=" More data " name="data[]" />
<input type="radio" value="3" name="data[]" />
<input type="input" value="" name="data[]" />

This will only work if all your rules are the same for every field.

Upvotes: 4

Related Questions