CodeIgniter Forums
Validate JSON? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Validate JSON? (/showthread.php?tid=80163)



Validate JSON? - wojtek_us - 09-22-2021

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().


RE: Validate JSON? - iRedds - 09-23-2021

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));


RE: Validate JSON? - wojtek_us - 09-23-2021

(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);