如果只满足2个标准,我们如何根据需要验证数组中的字段?
我在下面有一个示例数据,如果 candidate_type 为2或3且 is_present_company 为零,我想验证结束字段。
Array
(
[candidate_type] => 3,
[experience] => Array(
[0] => Array(
[job_title] => 'test title'
[company] => 'test company'
[start] => 'test start'
[end] => 'test end'
[is_present_company] => 1
[location_country] =>
)
)
)
这是我的Laravel验证码:
return Validator::make($data, [
'experience.*.job_title' => 'required_if:candidate_type,1,2',
'experience.*.company' => 'required_if:candidate_type,1,2',
'experience.*.start' => 'required_if:candidate_type,1,2|date',
'experience.*.end' => 'required_if:candidate_type,1,2|date',
'experience.*.location_country' => 'required_if:candidate_type,1,2',
]);
为了解决这个问题,我分别验证了数组字段。
$hasExperienceError = false;
if (!empty($data['candidate_type']) && in_array($data['candidate_type'], [1, 2])) {
if (empty($data['experience']) || count($data['experience']) < 1) {
// $validator->errors()->add('experience', 'Please provide at least one experience');
} else {
foreach($data['experience'] as $key => $z) {
$xv = Validator::make($z, [
'job_title' => 'required',
'company' => 'required',
'start' => 'required|date',
'end' => 'required_if:is_present_company,1|date',
'location_country' => 'required',
]);
if ($xv->fails()) {
$hasExperienceError = true;
}
}
}
}
答案 0 :(得分:0)
如果所需条件在其内部,则无法验证数组。您需要提取数组外部所需的字段,并将其用作数组的必需条件。
答案 1 :(得分:0)
注意:在下面的代码中 project_type。*用于验证数组
$ validate_response = Validator :: make($ data,array(
&#39; project_type *&#39; =&GT; &#39;需&#39 ;,
)
);
if ($validate_response->fails()) {
return redirect($request->url())->withErrors($validate_response)->withInput();
} else {
}