Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }

}
like image 631
Alister Greenpan Avatar asked Jul 16 '26 14:07

Alister Greenpan


1 Answers

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

}
like image 105
MaxiWheat Avatar answered Jul 19 '26 05:07

MaxiWheat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!