Laravel验证JSON

时间:2017-04-26 15:42:14

标签: php json laravel validation

我正在构建一个平台,用户可以使用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
}

期待您的想法!

1 个答案:

答案 0 :(得分:0)

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

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.');
}