CodeIgniter validates form with values ​​after array from database

I have a form with the 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]"> 
...
...

      

etc. with undefined number of lines and indices inside.

I cannot figure out how to check. I am trying in different ways, but I cannot guess:

$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');

      

etc.

I can't figure out how to manage it after the documentation of the form validation section. Can you help me? Thank you in advance!

I am storing fields to DB using foreach:

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

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

}

      

+3


source to share


1 answer


You can do it in different ways, you can iterate over the array of messages and add a rule for 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 copy your own validation as Codeigniter allows:

$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

}

      

+5


source







All Articles