Welcome Guest, Not a member yet? Register   Sign In
Validate JSON?
#1

(This post was last modified: 09-22-2021, 10:51 AM by wojtek_us.)

Hello,

Can CI4 validate JSON data using built-in functions?

I'm using fetch to send JSON to a controller, and everything is fine until I try adding validation rules and IF statement. I'm a hobbyst, so maybe there's something basic stuff I'm not aware of Smile.
Here's the start of my controller:

PHP Code:
if ($this->request->getMethod() === 'post')
        {

            // grab the JSON data
            $JSONdata $this->request->getJSON(true);

            $rules = [
                'photo_title' => 'required'
            ];

            if (! $this->validate($rules)) {
                // validation errors

                $this->data = [
                    'errors' => $this->validator->getErrors()
                ];

                $this->response->setContentType('Content-Type: application/json');
                $response json_encode($this->data);

                return $this->response->setJSON($response);
            


Validation "works", the getErrors() is saved within the response, and I keep getting the error "photo_title field is required". 
Here's the fetch JS:

Code:
fetch(URL, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                "X-Requested-With": "XMLHttpRequest"
            },
            body: JSON.stringify({
                photo_id: id,
                photo_title: title,
                photo_desc: desc
            })
        })
            .then((response) => response.json())
            .then((data) =>  console.log(data))
            .catch((error) => console.log(error));  // log error

The entire code works, I can save data from the form within the database until I add the validation IF statement. Can CI4 even recognize the photo_title from body: JSON.srtringify?

EDIT:

Figured it out, thanks to being stubborn Smile.

I didn't touch the fetch in javascript, but validation needed some changes, here's the validation code within the controller:

PHP Code:
// grab the JSON data
            $_POST $this->request->getJSON(true);

            $this->validation =  \Config\Services::validation();
            $this->validation->setRules([
                'photo_title' => 'required',
                'photo_desc' => 'required'
            ]);


            if (! $this->validation->run($_POST)) {
                // validation errors

                $this->data = [
                    'errors' => $this->validation->getErrors()
                ];

                $this->response->setContentType('Content-Type: application/json');
                $response json_encode($this->data);

                return $this->response->setJSON($response);
            

All I did was load the validation library into $this->validation variable and go from there with run().
Reply
#2

When you call $this->validate($rules), the method will automatically try to determine the content type and retrieve data for validation.

When you call $this->validation->run($_POST), you yourself define the data to validate. But if I am not mistaken, then with the content-type application/json, the $_POST array will be empty.

Call $this->validation->run($this->request->getJSON(true));
Reply
#3

(09-23-2021, 04:13 AM)iRedds Wrote: When you call $this->validate($rules), the method will automatically try to determine the content type and retrieve data for validation.

When you call $this->validation->run($_POST), you yourself define the data to validate.

That's what I figured out, though it took me some time Smile.

As for $_POST, I was trying different things, it was late, I assigned request to this super global. I guess I will change it later to something like $jsonData so it doesn't say $_POST. 

This should result in the following.

PHP Code:
$this->validation->run($jsonData); 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB