Laravel验证:必须是有效的JSON字符串,并带有"json"规则 [英] Laravel validation: Must be a valid JSON string with the "json" rule

查看:343
本文介绍了Laravel验证:必须是有效的JSON字符串,并带有"json"规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作Laravel API,但我似乎无法在其中一篇文章中发送JSON数据.我检查了StackOverflow中的其他帖子,但似乎我的JSON请求正确,所以我似乎找不到错误:

I'm making a Laravel API, but I can't seem to send JSON data in one of the posts. I checked the other posts in StackOverflow, but it seems that my JSON request is correct, so I can't seem to find the error:

这是我的Controller方法中的代码:

Here is the code in my Controller's method:

$validator = Validator::make($request->all(), [
    "name" => "required|string",
    "colors" => "json",
     "sizes" => "json"
]);

if($validator->fails())
    return response()->json(["errors" => $validator->errors()], 400);

这是请求正文:

{
 "name": "Test",
 "colors": {
   "Man": "#0000ff",
   "Second": "#FF0000"
 },
 "sizes": {
   "titles": "20px"
 }
}

错误:

{
   "errors": {
       "colors": ["The colors must be a valid JSON string."],
       "text_sizes": ["The text sizes must be a valid JSON string."]
   }
}

似乎是什么问题?谢谢!

What seems to be the problem? Thank you!

推荐答案

那么您需要传递JSON字符串而不是JSON对象.可以通过 json_encode JSON.stringify 完成.

Well you need to pass an JSON String instead of an JSON Object. This can be done either by json_encode or JSON.stringify.

作为对您的最后评论的答复.

As an answer on your last comment.:

您可以使用 JSON.stringify 在前端应用程序中执行此操作,也可以使用 prepareForValidation()实施表单请求:

You could either do this in your frontend application with JSON.stringify or you could implement an Form Request with an prepareForValidation(): https://laravel.com/docs/8.x/validation#prepare-input-for-validation.

在json属性上执行 json_encode()的位置.喜欢:

Where you would do an json_encode() on the json properties. Like:

protected function prepareForValidation()
{
    $this->merge([
        'colors' => json_encode($this->colors),
        'text_sizes' => json_encode($this->text_sizes)
    ]);
}

或者您的情况:

$validator = Validator::make($request->merge([
        'colors' => json_encode($request->colors),
        'text_sizes' => json_encode($request->text_sizes)
    ]), [
    "name" => "required|string",
    "colors" => "json",
     "sizes" => "json"
]);

这篇关于Laravel验证:必须是有效的JSON字符串,并带有"json"规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆