【问题标题】:Multiple array validation in laravellaravel 中的多数组验证
【发布时间】:2017-08-09 03:30:13
【问题描述】:

我有 3 种类型的数据要验证

  1. 组中的数据
  2. 单个数据
  3. 单个和组内数据合并

此验证适用于单个数据

$validator = Validator::make($request->all(), [
    'tests.*.finding' => 'required',//works for single test
]);

以上数据示例

["tests"=>
                [
                    0 => ["finding"=>""]
                ],
                [
                    1 => ["finding"=>""]
                ]
            ]

此验证适用于组中的数据

$validator = Validator::make($request->all(), [
    'tests.*.*.finding' => 'required',//works for group
]);

以上数据示例

  ["tests"=>
                    [
                        "A" =>[
                            [
                                0 => ["finding"=>""]
                            ],
                            [
                                1 => ["finding"=>""]
                            ]
                        ],
                        "B" =>[
                            [
                                0 => ["finding"=>""]
                            ],
                            [
                                1 => ["finding"=>""]
                            ]
                        ]
                    ]
                ]

如何验证单个和组中的数据组合

组合数据样本

 ["tests"=>
                    [
                        "A" =>[
                            [
                                0 => ["finding"=>""]
                            ],
                            [
                                1 => ["finding"=>""]
                            ]
                        ]
                    ],
                    [
                        0 => ["finding"=>""]
                    ],
                    [
                        1 => ["finding"=>""]
                    ]
                ]

请帮我解决这个问题,因为第一个场景总是给场景第二个错误,反之亦然。

【问题讨论】:

  • 使用验证规则可能无法做到这一点。如果更简单,您可以创建自定义验证器或将组合数据拆分为前 2 个示例。

标签: php laravel validation laravel-5 laravel-validation


【解决方案1】:

这就是解决方案,Laravel 提供了sometimes 规则来管理元素的存在,然后只继续检查下一条规则。

所以最终的验证规则是。

 $validator = Validator::make($request->all(), [
 'tests.*.*.finding' => 'sometimes|required',//works for group
 'tests.*.finding' => 'sometimes|required',//works for single test
 ]);

文档:https://laravel.com/docs/5.4/validation#conditionally-adding-rules

【讨论】:

  • 太棒了!很高兴你找到了解决方案,有趣的案例。
【解决方案2】:

您可以按照代码来修复验证数据。

$customFieldValidation = ["test_id" => 'required|numeric',
        "test_two.id" => 'required|numeric',        
        ]);     
  $this->setRules ( $customFieldValidation );  
  $customeAttributes = [
  "test_three.*.id" => 'Test Three ' // custom message
  ];
  $this->setCustomAttributes ($customeAttributes);
  $this->_validate ();

希望对你有帮助。

【讨论】:

  • 你对sometimes规则有什么看法?
猜你喜欢
  • 1970-01-01
  • 2014-09-13
  • 2019-02-21
  • 2020-08-06
  • 2019-01-14
  • 2018-01-03
  • 1970-01-01
  • 2016-04-28
  • 2014-01-28
相关资源
最近更新 更多