Alister Greenpan
Alister Greenpan

Reputation: 133

CodeIgniter validate form with post array values from the database

I have a form with following structure:

Field A: <input name="something[34]"> -- Field B: <input name="something_else[11]">
Field A: <input name="something[93]"> -- Field B: <input name="something_else[67]">
Field A: <input name="something[5]"> -- Field B: <input name="something_else[212]"> 
...
...

and so on with undefined number of rows and indexes values inside.

I cannot figure it out how to validate. I am trying different ways but I cannot guess it:

$this->form_validation->set_rules('something[]', 'Something', 'required|xss_clean');
$this->form_validation->set_rules($_POST[something[]], 'Something', 'required|xss_clean');
$this->form_validation->set_rules($_POST[something][], 'Something', 'required|xss_clean');

and so on..

I cannot figure it out how to manage it following the documentation of the form validation section. Can you give me some help with this? Thank you in advance!

I save the fields back in the DB with foreach:

foreach ($_POST['something'] as $something_id => $something_name) {

    if ($this->form_validation->run() === TRUE) {
        //insert
    }

}

Upvotes: 3

Views: 3385

Answers (1)

MaxiWheat
MaxiWheat

Reputation: 6251

You can do this in many ways, you could loop over the array of post items and add a rule on each (depending on what kind of validation you need)

$this->form_validation->set_rules('something[]', 'Something', 'required|xss_clean'); // Ensure something was provided

if (is_array($_POST['something'])) {
    foreach ($key as $key => $value) {
        $this->form_validation->set_rules('something['.$key.']', 'Something', 'required|greater_than[10]|xss_clean'); // Any validation you need
    }
}

You can also code your own custom validation as Codeigniter allows it :

$this->form_validation->set_rules('something[]', 'Something', 'callback_something_check');

...

function something_check($something) {
    // Do what you need to validate here

    return true; // or false, depending if your validation succeeded or not

}

Upvotes: 5

Related Questions