【问题标题】:Laravel validate JSONLaravel 验证 JSON
【发布时间】:2017-09-24 03:07:00
【问题描述】:

我正在构建一个平台,用户可以在其中使用 REST API 创建订单。

我注意到,当您对 JSON 数据进行“畸形”处理时,它不会引发错误,而是会返回所有验证错误,例如

{
    "supplier_id": 1,
    "firstname": "john",
    "lastname": "doe",
    "street": "janestreet",
    "number": 11,
    "city": "the city",
    "country": "BEL"", // <-- double closing quotes
}

这只是返回所有验证错误,就好像什么都没通过一样。

  {
    "firstname": [
      "The firstname field is required."
    ],
    "lastname": [
      "The lastname field is required."
    ],
    "street": [
      "The street field is required."
    ],
    "number": [
      "The number field is required."
    ],
    "city": [
      "The city field is required."
    ],
    "country": [
      "The country field is required."
    ],
    "items": [
      "The items field is required."
    ]
  }

我试过了

if(!$request->isJson()) {
    //return invalid response
}

期待你的想法!

【问题讨论】:

  • 我会保持原样。用户发布了格式错误的数据,因此 API 没有它需要的任何这些数据字段。由用户决定是否发送有效的 JSON。
  • 你能显示你的验证规则吗

标签: php json laravel validation


【解决方案1】:

您可以在app/Providers/AppServiceProvider.php 中的boot 方法中添加类似的内容。

Validator::extend('valid_json', function ($attributes, $value, $parameters, $validation) {
    $json_string = $value;

    if(!is_string($json_string)) {
        return false;
    }
    json_decode($string);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return false;
    }
    return true;
});

试试这样的:

$validator = Validator::make([
    'my_json' => $your_json_to_validate_from_post_or_file_etc,
], [
    'my_json' => 'required|valid_json'
];

if ($validator->fails()) {
    //
}

更一般地说,它可以在自定义Request 中使用类似这样的东西:

public function rules()
{
    return [
        'something' => 'required|valid_json',
    ];
}

或在控制器中:

$validator = Validator::make($input_values, [
    'something' => 'required|valid_json',
]);

if ($validator->fails()) {
    throw new Exception('JSON was invalid.');
}

【讨论】:

  • 感谢您的回答,但这是一个 POST BODY json,而不是发布的属性,请参阅下面的帖子 :)
  • 我不明白,格式错误的 json 究竟来自哪里?我更新了我的答案,也许现在你会更清楚?
  • 我对我的 Laravel 应用程序类型为 application/json 的 API POST 请求,但 json 格式错误。
  • 你能再贴一些代码吗?你期望发生什么?
  • @Notflip 为什么不只发送格式正确的 JSON?
猜你喜欢
  • 2017-10-15
  • 2015-01-31
  • 1970-01-01
  • 2018-10-13
  • 2021-09-08
  • 2017-10-19
  • 2019-11-16
  • 2018-02-23
  • 2016-02-22
相关资源
最近更新 更多