【问题标题】:Codeigniter, using Form validation for no POST dataCodeigniter,对无 POST 数据使用表单验证
【发布时间】:2017-11-12 12:37:25
【问题描述】:

我正在使用 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") 之类的关联数组

【问题讨论】:

  • Ops,我从来没有读过那一段。对于关联数组?
  • 没关系,直到我去寻找之前我都没有,因为这是一个有趣的问题:)
  • 那么,有什么解决方案可以为 validation_errors() 创建关联数组吗?

标签: php codeigniter


【解决方案1】:

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

现在您可以通过$this->form_validation->error_array() 获取表单验证错误数组。您也可以自定义错误信息(留给您查找)

基于名为 rest_app 的控制器 /rest_app?firstValue=val&secondValue=2 index 方法可能看起来像这样 - 带有调试。

更改您需要的内容,使其适合您的需求。这只是一个小演示代码。

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.
    }
}

【讨论】:

    猜你喜欢
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2016-09-26
    • 2015-07-23
    • 1970-01-01
    • 2016-05-17
    相关资源
    最近更新 更多