CodeIgniter使用数据库中的post数组值验证表单

Ali*_*pan 3 php codeigniter

我有一个结构如下的表格:

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]"> 
...
...
Run Code Online (Sandbox Code Playgroud)

等等,里面有未定义的行数和索引值.

我无法弄清楚如何验证.我正在尝试不同的方式,但我猜不出来:

$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');
Run Code Online (Sandbox Code Playgroud)

等等..

根据表单验证部分的文档,我无法弄清楚如何管理它.你能帮我个忙吗?先感谢您!

我用foreach将字段保存在DB中:

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

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

}
Run Code Online (Sandbox Code Playgroud)

Max*_*eat 5

您可以通过多种方式执行此操作,您可以遍历帖子项目数组并在每个项目上添加规则(取决于您需要的验证类型)

$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
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以编写自己的自定义验证,因为Codeigniter允许它:

$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

}
Run Code Online (Sandbox Code Playgroud)