Can you please show an example request data and your validation code so we can try to help?
Form Request Validation for JSON Parameter
Hi there,
I have an AJAX request sent to my API. This request has a parameter that should contain a JSON formatted data. I want to validate that it is actually JSON. Laravel form request has a 'json' validation rule, but the problem I am facing is that the parameter that I want to validate for JSON gets converted into an array before validation. So how am I supposed to prevent this conversion and do the validation?
Example request data:
{
"id": 1,
"name": "John",
"json_data": {
"data1": [
],
"data2": [
]
}
}
validation:
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'id' => [
'required'
],
'title' => [
'required',
'string',
],
'json_data' => [
'required',
'json',
],
];
}
So the json rule validates a JSON string for a valid JSON, so the data that you are sending should be like this instead:
{
"id": 1,
"name": "John",
"json_data": "{\"data1\": [], \"data2\": []}"
}
You should be able to achieve that on your JS side using JSON.stringify(jsonData);
Please or to participate in this conversation.