我有两个复选框字段tech
和active
,我想成为nullable
,但我也希望可以将输入的值限制为一个字段的单个值,并且另一个字段的两个值之一。
我遇到了答案stackoverflow,但我似乎没有正确实现它。这是我的代码:
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:150',
'email' => 'required|string|max:200',
'phone' => 'required|digits:11',
'branch' => 'required|string',
'department' => 'required|string',
'tech' => ['nullable','digits:1', Rule::in([1, 2])],
'role' => 'required|string',
'active' => ['nullable', 'string', 'max:6', Rule::in(['active'])]
]);
如果我这样做:
'tech' => 'nullable|digits:1',
'active' => 'nullable|string|max:6'
它可以工作,但是我需要验证这些字段可以允许的值。
答案 0 :(得分:1)
Chin Leung通过注释部分的实现为我解决了这个问题。
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:150',
'email' => 'required|string|max:200',
'phone' => 'required|digits:11',
'branch' => 'required|string',
'department' => 'required|string',
'tech' => 'nullable|digits:1|in:1,2',
'role' => 'required|string',
'activate' => 'nullable|string|max:6|in:active'
]);
答案 1 :(得分:0)
您甚至可以在验证器类中将闭包传递给验证器。
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:150',
'email' => 'required|string|max:200',
'phone' => 'required|digits:11',
'branch' => 'required|string',
'department' => 'required|string',
'tech' => function($attribute, $value, $fail){
if (isset($value)) {
sizeof($value) > 1 ?? return $fail($attribute." is invalid");
in_array($value, [1,2]) ?? return $fail($attribute." is invalid");
}
},
'role' => 'required|string',
'active' => ['nullable', 'string', 'max:6', Rule::in(['active'])]
]);