如何在验证回调函数中访问数组字段名称值?

时间:2012-10-22 04:53:17

标签: php validation codeigniter frameworks

我在视图中收到了一些文字输入:

<label for="car-n">Car Name:</label><input type="text" name="cars[]" id="car-n"/>
<label for="car-t">Car Type:</label><input type="text" name="cars[]" id="car-t"/>

现在,我想用CodeIgniter的验证回调函数验证它们,但似乎我无法获得它们的值:

$this->form_validation->set_rules('cars[]', 'Cars', 'required|xss_clean|callback__validate_cars');

...和功能:

function _validate_cars($input)
{
     echo $input; //returns no field value;
     echo $this->form_validation->set_value('cars[]'); //not works
}

那么,我应该如何在回调函数中访问这两个字段值呢?我在CodeIgniters用户指南中没有看到有关此案例的任何信息。

1 个答案:

答案 0 :(得分:1)

好的,看下面的控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Temp extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->library(array('form_validation'));
    }

    public function index()
    {
        $this->show_form();
    }



    public function validate(){
        $this->form_validation->set_rules('cars[]', 'Cars', 'required|callback_validate_cars');
        if ($this->form_validation->run() == FALSE)
        {
            $this->show_form();

        }
        else "All is ok";
    }

    public function validate_cars($string)
    {
        print_r($this->input->post('cars'));
        return false;
    }

    public function show_form()
    {
        echo '<form action="'. base_url('temp/validate').'" method="post">';
        echo 'Car 1: <input name="cars[]" type="text">';
        echo ' Car 2: <input name="cars[]" type="text">';
        echo '<input type="submit" value="Go!">';
        echo '</form';
    }
}

您可以将帖子值用作$this->input->post('cars');