【问题标题】:codeigniter form validation always false with json datajson数据的codeigniter表单验证总是错误的
【发布时间】:2013-08-29 00:49:41
【问题描述】:

我正在使用 codeigniter 构建自己的 REST Web 服务,该应用程序有一个名为“calls”的资源,可以通过 POST 方法访问它, p>

calls”函数通过 Curl 调用使用此 content-type 接收四个参数 [id、manager、department、level] 作为 json 对象:application/json

然后我使用 codeigniter form_validation() 库来验证请求,如果 form_validation()

上没有错误,则返回响应数组

问题是 form_validation() 总是返回 FALSE,尽管我可以按预期输出接收到的值。

下面是调用函数的代码

function calls_post() {

$this->load->model('api/central');
$this->load->library('form_validation');

//validation rules
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('id', 'id', 'required|numeric');
$this->form_validation->set_rules('manager', 'manager', 'required|numeric');
$this->form_validation->set_rules('department', 'department', 'required');
$this->form_validation->set_rules('level', 'level', 'required|numeric');


if ($this->form_validation->run() === FALSE) {

    $employeeId = $this->form_validation->error('id') ? $this->form_validation->error('id') : $this->post('id');
    $manager = $this->form_validation->error('manager') ? $this->form_validation->error('manager') : $this->post('manager');
    $department = $this->form_validation->error('department') ? $this->form_validation->error('department') : $this->post('department');
    $level = $this->form_validation->error('level') ? $this->form_validation->error('level') : $this->post('level');

    $response = array(
        'status' => FALSE,
        'error' => 'We don\'t have data to display, Minimum information required to process the request is missing',                
        'authenticated' => true,                
        'id' => $employeeId,
        'manager' => $manager,
        'department' => $department,
        'level' => $level                
    );

    $this->response($response, 200);

} else {

    $response = $this->central->calls_get($this->post('id'), $this->post('manager'), $this->post('department'), $this->post('level'));
    $this->response($response);
}
}

有什么建议吗? :)

【问题讨论】:

    标签: codeigniter rest


    【解决方案1】:

    http://ellislab.com/forums/viewthread/238080

    $_POST = json_decode(file_get_contents("php://input"), true);
    $this->form_validation->set_rules('id', 'id', 'required|numeric');
    $this->form_validation->set_rules('department', 'department', 'required');
    
    if($this->form_validation->run() == TRUE)
    {   
        $id = $this->input->post('id'); 
        $department = html_escape($this->input->post('department'));    
        echo $id."<br>".$department;       
    }
    else
    {   
        echo "false";        
    }
    

    【讨论】:

    • 非常感谢你的朋友。当我们在服务器上发出 curl 发布请求时,我正在尝试执行表单验证。
    • 太棒了,所以默认情况下 ci3 form_validator 不支持 json pyload 对吧?
    猜你喜欢
    • 2012-07-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多