首页 > 解决方案 > Laravel 验证 - 三个中的一个必须是真的吗?

问题描述

我正在研究如何以一种不丑陋的方式做到这一点。

['input1'=>true, 'input2'=>false, 'input3'=> false] // valid

['input1'=>false, 'input2'=>false, 'input3'=> false] // not valid
['input1'=>null, 'input2'=>true, 'input3'=> false] // not valid
['input1'=>true, 'input2'=>true, 'input3'=> false] // not valid

这似乎真的很简单 - 只有当一个选项为true时,输入才有效,而另一个选项是false(不是null)。

谁能帮我做到这一点?

(Laravel 5.7 仅供参考)

标签: laravelvalidation

解决方案


最终解决了。

我需要在表单请求中覆盖 getValidatorInstance 方法:

/**
 *  Override the validator instance
 */
protected function getValidatorInstance()
{
    return parent::getValidatorInstance()->after(function ($validator) {

        $trueAttributes = 
            collect(request()->only('input1','input2','input3'))
            ->reject(function($attribute){
                return ($attribute !== true);
            });

        if ($trueAttributes->count() !== 1) {
            $validator->errors()->add('data', 'At least one attribute must be true');
        }
    });
}

推荐阅读