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 . Here's the start of my controller: PHP Code: if ($this->request->getMethod() === 'post') 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, { 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 . 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 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. That's what I figured out, though it took me some time . 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); |