【问题标题】:How to validate a JSON post with Dingo API in Laravel?如何在 Laravel 中使用 Dingo API 验证 JSON 帖子?
【发布时间】:2019-02-19 18:56:45
【问题描述】:

我正在尝试使用 Laravel 中的 Dingo API 库验证我通过帖子获取的 json。似乎验证工作不正确,因为我根据我正在验证的字段发送了一个有效的 JSON,它返回给我的消息是:

X 字段是必需的。

但是我在json中发送X字段,我不明白。

JSON:

    [
      {
        "currency_id": 1,
        "bills": [
            {
                "barcode": "99999.9999999.99999999.9999 9",
                "due_date": "2018-09-14",
                "value": 70.00
            },
            {
                "barcode": "8888.888888.88888.8888 8",
                "due_date": "2018-09-15",
                "value": 32.00
            }
        ]
    }
]

我收到此错误:

"message": "422 Unprocessable Entity",
"errors": {
    "currency_id": [
        "The currency id field is required."
    ],
    "bills": [
        "The bills field is required."
    ]
},

这是我的带有验证规则的自定义 FormRequest,我将它作为参数传递给 BillController 存储方法。

namespace App\Http\Requests;

use App\Rules\Sum;
use Dingo\Api\Http\FormRequest;


class BillRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'currency_id' => 'required|integer|exists:currency,id',
            'bills' => ['required', 'array', 'min:1', 'max:3', new Sum],
            'bills.*.barcode' => 'required|string|min:10|max:255',
            'bills.*.due_date' => 'date',
            'bills.*.value' => 'required|numeric|between:10,30000',
        ];
    }


}

【问题讨论】:

  • 确保post请求有这个头Content-Type: application/json
  • 您的对象位于数组中尝试*.currency_id
  • 谢谢,我能够验证currency_id 字段,但我无法验证作为数组的第二个bill 字段,如何验证bills 中的数组?
  • 事实上没有验证工作,它直接来自验证,即使我发送一个空的 json
  • 我设法解决了它,我会发布它的答案。

标签: php laravel


【解决方案1】:

为了解决我不得不把 *.在每条规则前面,因为我得到一个数组,所以验证器只能这样理解。

public function rules()
{
    return [
        '*.currency_id' => 'required|integer|exists:currency,id',
        '*.bills' => ['required', 'array', 'min:1', 'max:3', new Sum],
        '*.bills.*.barcode' => 'required|string|min:10|max:255',
        '*.bills.*.due_date' => 'date',
        '*.bills.*.value' => 'required|numeric|between:10,30000',
    ];
}

【讨论】:

    猜你喜欢
    • 2017-01-16
    • 2017-06-02
    • 2016-05-04
    • 1970-01-01
    • 2017-11-13
    • 2019-02-14
    • 2018-11-13
    • 1970-01-01
    • 2016-07-22
    相关资源
    最近更新 更多