代码之家  ›  专栏  ›  技术社区  ›  POV

哪些数据发送错误?

  •  0
  • POV  · 技术社区  · 7 年前

    我的传入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',
        ];
    }
    

    我经常会遇到一个常见的错误:错误的数据验证

    0 回复  |  直到 7 年前
        1
  •  3
  •   Kenny Horna    7 年前

    如果您仔细检查验证规则,特别是:

    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 文件的完整性。