簡體   English   中英

Codeigniter,對沒有POST數據使用表單驗證

[英]Codeigniter, using Form validation for no POST data

我正在使用CodeIngiter創建一個寧靜的應用程序。

我想知道是否可以對非$ _POST數據使用FormValidation類。

我在想:如果客戶端以這種方式發送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(); ?> <?php echo validation_errors(); ?>具有關聯數組,例如array('firstValue' => "The field secondValue must be integer")

根據我的評論-您可以將關聯數組傳遞給表單驗證,而不是使用默認的$ _POST數組。

現在,您可以通過$this->form_validation->error_array()獲得表單驗證錯誤數組。 您還可以自定義錯誤消息(留給您查找)

基於名為rest_app / rest_app?firstValue = val&secondValue = 2的控制器,索引方法可能看起來像這樣-帶有調試功能。

更改所需的內容,使其適合您的需求。 這只是一些演示代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM