3

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
    }

}

1 Answer 1

5

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.