Codeigniter,使用表单验证没有POST数据

时间:2017-11-12 12:37:26

标签: php codeigniter

我正在使用CodeIngiter来创建一个安静的应用程序。

我想知道是否可以将FormValidation类与非$ _POST数据一起使用。

我在想:如果客户端以这种方式发送GET请求:

https://myrestapp.com/controller?firstValue=val&secondValue=val2

如何使用以下方法验证firstValue和secondValue:

//example
$this->form_validation->set_rules('firstValue', , 'required');
$this->form_validation->set_rules(secondValue, , 'required|integer');

并且,如何将<?php echo validation_errors(); ?>转换为像array('firstValue' => "The field secondValue must be integer")

这样的关联数组

1 个答案:

答案 0 :(得分:0)

根据我的评论 - 您可以将关联数组传递给表单验证,而不是使用默认的$ _POST数组。

现在,您可以通过$this->form_validation->error_array()获取表单验证错误数组。您还可以自定义错误消息(左侧供您查找)

基于名为rest_app的控制器 / rest_app firstValue = VAL&安培; secondValue = 2 索引方法可能看起来像这样 - 使用debug。

改变您需要的东西,使其符合您的需求。这只是一个小小的演示代码。

public function index() {
    $this->load->library('form_validation');
    // Need to test this exists?
    $str = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : NULL;
    if ($str !== NULL) {
        // Grab the Query string and turn it into an associative array
        parse_str($str, $url_query_array);
        // DEBUG - Check the array looks correct
        var_dump($url_query_array);

        // Give the form validation the fields/Values to work with.
        $this->form_validation->set_data($url_query_array);

        // Now for the Validation Rules
        $this->form_validation->set_rules('firstValue', 'firstValue', 'required');
        $this->form_validation->set_rules('secondValue', 'secondValue', 'required|integer');

        // Did we get a valid
        if ($this->form_validation->run()) {
            echo "We got what we wanted, so do some stuff"; // DEBUG ONLY
            // add your code here

        } else {
            echo "Well that didn't work well.";
            $error_associative_array = $this->form_validation->error_array();
            var_dump($error_associative_array); // DEBUG ONLY
            // Send $error_associative_array back as a response
        }

    } else {
        echo "No query string present";
        // Handle this as an error condition or die silently.
    }
}
相关问题