在我的 Controller 上我有:
public function store(ProductRequest $request)
请求:
class ProductRequest extends Request
{
public function rules()
{
return [
'name' => 'required|min:3',
'perTypeTime' => 'sometimes|required',
'per_type_id' => 'required'
];
}
}
我想根据 per_type_id field == 1 将上面的 perTypeTime 规则更改为有条件的。
如果我在 Controller 中启动验证器,我相信我可以执行以下操作:
$v = Validator::make($data, [
'per_type_id' => 'required|email'
]);
$v->sometimes('perTypeTime', 'required|max:500', function($input)
{
return $input->per_type_id == 1;
});
有没有办法做到这一点,同时保留我的自定义请求。我喜欢这种方法如何使 Controller 保持清洁。
我似乎无法访问请求对象上的验证器。有没有办法在请求本身中指定这个条件,或者从请求对象访问验证器,或者有其他方法吗?
最佳答案
你可以这样做
I want to change the perTypeTime rule above to be conditional depending on if per_type_id field == 1.
在 ProductRequest
的 rules()
方法中。
有关详细信息,请参阅 Laravel documentation validation rules 中的 required_if:anotherfield,value .
public function rules()
{
return [
'name' => 'required|min:3',
'perTypeTime' => 'required_if:per_type_id,1',
'per_type_id' => 'required'
];
}
关于php - 自定义表单请求的条件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37240761/