简体   繁体   中英

Codeigniter, using Form validation for no POST data

I'm using CodeIngiter to create a restful app.

I was wondering if is it possible to use the FormValidation class with a non $_POST data.

I was thinking: if the client send a GET request in this way:

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

how can I validate firstValue and secondValue using this:

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

and, how can I convert <?php echo validation_errors(); ?> <?php echo validation_errors(); ?> with an associative array like array('firstValue' => "The field secondValue must be integer")

As per my comment - you can pass an associative array to the form validation instead of using the default $_POST array.

Now you can get at the form validation errors array via $this->form_validation->error_array() . You can also customise the error messages ( Left for you to look up )

Based upon a controller called rest_app /rest_app?firstValue=val&secondValue=2 the index method might look like this - with debug.

Change what you need to, to make it suit your needs. This is just a little demo code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM