I would like to validate the following json in CI4:
{
"field1": "some value",
"array1": {
"2876": "4358",
"9904": "17"
}
}
Array 1 can reasonably contain up to 50 key value pairs.
I have validation rules for both the keys and values in array1, for the purposes of this question lets require them both to be numeric.
The code I have so far is:
$validation = \Config\Services::validation();
$validation->setRules([
'field1' => 'required|max_length[20]',
'array1.*' => 'required|numeric',
]);
if (! $validation->withRequest($this->request)->run()) {
return $this->failValidationErrors($validation->getErrors());
}
Alternatively based on an answer I've seen elsewhere:
$validation = \Config\Services::validation();
$validation->setRules([
'field1' => 'required|max_length[20]'
]);
$to_validate = $this->request->getPost();
foreach ($to_validate['array1'] as $key => $value) {
$validation->setRule('array1.' . $key , null, 'required|numeric');
}
if (! $validation->withRequest($this->request)->run()) {
return $this->failValidationErrors($validation->getErrors());
}
This code successfully rejects a value of "abcd" but how do I reject a string key?
I could pre-process by putting the keys into their own array which can be validated with an array2.* rule but this seems like a simple use case which should work out of the box.
Also how should I implement the array size limit check?