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')
{
// 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
.
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().