我发送哪些数据错误?

时间:2019-05-02 23:56:52

标签: php laravel laravel-5

我传入的JSON对象:

{
    "date": "2018-10-10", 
    "fiche": 1, 
    "fiche_type": 2, 
    "description": "test", 
    "project_code": "444", 
    "invoces": 
    [
        {
            "id": 1,
            "description": "Ol",
            "amount": 300,
            "type": "debit"
        },
        {
            "id": 2,
            "type" :"credit",
            "description": "Ol2",
            "amount": 200
        }
    ]
}

验证规则为:

public function rules()
{

    return [
        'date' => 'required|date_format:Y-m-d',
        'fiche' => 'required|integer',
        'fiche_type' => 'required|integer',
        'description' => 'string',
        'project_code' => 'string',
        'invoices' => 'required|array',
        'invoices.id' => 'required|integer',
        'invoices.description' => 'string',
        'invoices.amount' => 'required|numeric',
        'invoices.type' => 'required|string',
    ];
}

我总是会遇到以下常见错误:错误的数据验证

1 个答案:

答案 0 :(得分:3)

如果您仔细检查验证规则,具体是:

return [
    // ...
    'invoices' => 'required|array',
    'invoices.id' => 'required|integer', // <---
    'invoices.description' => 'string', // <---
    'invoices.amount' => 'required|numeric', // <---
    'invoices.type' => 'required|string', // <---
];

使用该设置,类似的东西应该通过验证(至少是该部分):

$invoices = [
        'id' => 123,
        'description' => 'a description',
        'amount' => 123,
        'type' => 'a type',
    ];

但这不是您想要的 ..您需要实际验证具有以下结构的项目(数组):

$invoices = [
    [
        'id' => 123,
        'description' => 'a description',
        'amount' => 123,
        'type' => 'a type',
    ],
    [
        'id' => 345,
        'description' => 'another description',
        'amount' => 156,
        'type' => 'another type',
    ],
];

所以..什么问题?

好吧,在项目键之前,您需要访问项目本身的,但是鉴于此规则将适用于数组中的每个项目,因此您需要使用通配符。如文档所述:

  

您还可以验证数组的每个元素。例如,   验证给定数组输入字段中的每个电子邮件都是唯一的,您   可以执行以下操作:

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);
     

同样,您可以在指定验证时使用*字符   语言文件中的邮件,轻松使用单个   基于数组的字段的验证消息:

'custom' => [
    'person.*.email' => [
        'unique' => 'Each person must have a unique e-mail address',
    ] ],

所以在您的情况下:

return [
    // ...
    'invoices' => 'required|array',
    'invoices.*.id' => 'required|integer', // <---
    'invoices.*.description' => 'string', // <---
    'invoices.*.amount' => 'required|numeric', // <---
    'invoices.*.type' => 'required|string', // <---
];

检查文档的Validation Arrays section