Laravel:每条规则的递归验证

时间:2017-11-21 17:49:12

标签: php laravel validation recursion laravel-5

我正在管理面板上工作,管理员可以为会员申请设置验证自定义验证规则。我理解需要设置$ attribute =>数据库中的$ rules对。

但是,有一个请求的功能我不太确定如何实现。管理员想要每个$ key => $ rule对递归并且可选地有子元素$ key =>如果父级失败将执行的$规则对。因此,最后,每个规则都可能有0到多个子规则,这些规则都需要传递才能使父规则通过。

示例:

// Original validation (Assume age = 16, time_at_job = 18 and monthly_income = 3000)
[
    'age' => 'min:21', // Fail, but pass because of subset is all pass
    'time_at_job' => 'min:6' // Pass
    'monthly_income' => 'min:2000' // Pass
]

// If the original age fails and this passes, then age passes and continue to the original 
time_at_job.
[
    'age' => 'min:18, // Fail, but pass because of subset is all pass
    'time_at_job' => 'min:12' // Pass
    'monthly_income' => 'min:2500' // Pass
]

// If the subset age passed and this passes, then the subset age passes, but the subset 
time_at_job and monthly income will need to pass before the original age can pass.
[
    'age' => 'min:16, // Pass
    'time_at_job' => 'min:18' // Pass
    'monthly_income' => 'min:3000' // Pass
]

非常感谢任何从这里开始的帮助。

1 个答案:

答案 0 :(得分:0)

我想你可以使用方法调用作为数组值,比如

public function rules(){
    return [
     'age' => $this->ageChildCheck(),
    ]
}

然后在验证器中的规则之后:

public function ageChildCheck(){
    $data = $this->validationData();
    if($data['time_at_job'] > passNumber && $data['monthly_income'] > passNumber2){
        return 'min:0';
    }else{
        return 'min:18';
    }
}

应该允许您可变地设置验证规则到底是什么。如果条件满足则自动通过,将其设置为0,失败时自动通过18。