Laravel:当输入是数组时使用验证器的有时方法

时间:2019-02-06 08:06:47

标签: php arrays laravel validation laravel-5.2

我有一个表单,该表单以数组形式发布了structure字段。 structure数组包含数据库表列的定义。

$validator = Validator::make($request->all(), [
    'structure' => 'required|array|min:1',
    'structure.*.name' => 'required|regex:/^[a-z]+[a-z0-9_]+$/',
    'structure.*.type' => 'required|in:integer,decimal,string,text,date,datetime',
    'structure.*.length' => 'nullable|numeric|required_if:structure.*.type,decimal',
    'structure.*.default' => '',
    'structure.*.index' => 'required_if:is_auto_increment,false|boolean',
    'structure.*.is_nullable' => 'required_if:is_auto_increment,false|boolean',
    'structure.*.is_primary' => 'required_if:is_auto_increment,false|boolean',
    'structure.*.is_auto_increment' => 'required_if:structure.type,integer|boolean',
    'structure.*.is_unique' => 'required_if:is_auto_increment,false|boolean',
    'structure.*.decimal' => 'nullable|numeric|required_if:structure.*.type,decimal|lt:structure.*.length',
]);

在不解释所有规则的情况下,应确保当length不是null或{{时,type字段始终为string 1}},因为您不能为这些类型以外的其他列分配长度。因此,我尝试在decimal实例上使用sometimes方法。

$validator

我的问题是在闭包内部,如何确保$validator->sometimes('structure.*.length', 'in:null', function ($input) { // how to access the structure type here? }); 仅对于length设置为null以外的数组元素为typestring

我尝试了decimal函数,似乎整个输入数组都传递给了闭包。

dd

这是$validator->sometimes('structure.*.length', 'in:null', function ($input) { dd($input); }); 方法的输出。

Output of the <code>dd</code> method

我可以使用dd构造,但是效率不高吗?检查所有元素中的单个元素?

如何仅检查所考虑的数组元素的类型?

有Laravel方法可以做到吗?

2 个答案:

答案 0 :(得分:0)

这是一个很好的问题。我看了sometimes()的API。您目前似乎无法执行您想做的事情。

一种可能的替代方法是使用验证钩后。例如:

$validator->after(function ($validator) {
    $attributes = $validator->getData()['structure'];

    foreach($attributes as $key => $value) {
        if(! in_array($value['type'], ['string', 'decimal']) && ! is_null($value['length'])) {
            $validator->errors()->add("structure.{$key}.length", 'Should be null');
        }
    }
});

答案 1 :(得分:0)

相反的想法怎么样?如果类型为字符串或十进制,则“长度”字段将变为必填。

events.js:187
      throw er; // Unhandled 'error' event
      ^

Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented
    at Readable._read (_stream_readable.js:647:24)
    at Readable.read (_stream_readable.js:490:10)
    at maybeReadMore_ (_stream_readable.js:634:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on Readable instance at:
    at errorOrDestroy (internal/streams/destroy.js:108:12)
    at Readable._read (_stream_readable.js:647:3)
    at Readable.read (_stream_readable.js:490:10)
    at maybeReadMore_ (_stream_readable.js:634:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'ERR_METHOD_NOT_IMPLEMENTED'