代码之家  ›  专栏  ›  技术社区  ›  Noman Ur Rehman

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

  •  5
  • Noman Ur Rehman  · 技术社区  · 6 年前

    我有一张表格 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 decimal 因为不能为这些类型以外的列指定长度。所以,我想用 sometimes 方法论 $validator 实例。

    $validator->sometimes('structure.*.length', 'in:null', function ($input) {
        // how to access the structure type here?
    });
    

    长度 无效的 仅适用于具有 类型 设置为除 一串 十进制的 .

    我试过 dd 函数,似乎整个输入数组都传递给闭包。

    $validator->sometimes('structure.*.length', 'in:null', function ($input) {
        dd($input);
    });
    

    以下是 方法。

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

    我可以用一个 foreach 但这不是效率低下吗?检查单个元素的所有元素?

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

    有什么办法可以这么做吗?

    1 回复  |  直到 5 年前
        1
  •  0
  •   Mozammil    6 年前

    这是个很好的问题。我看了一下 sometimes() . 看来,你想做什么,目前是不可能的。

    可能的选择 能够 使用 . 例如:

    $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');
            }
        }
    });
    
        2
  •  0
  •   Hayato    5 年前

    $validator->sometimes('structure.*.length', 'required', function ($input) {
        return $input->type == 'string' or $input->type == 'decimal';
    });