所以我有一个包含动态字段communication_type_id和communication_value的表。如果用户选择communication_type_id = 4,那么communication_value应该是必需的电话号码,如果用户选择则是数字 Communication_type_id = 7然后应该要求communication_value和email.How我这样做?我已经完成了直到现在,但它似乎没有检查条件,因为我得到“communication_value必须是一个有效的电子邮件地址”两个条件:
$validator = Validator::make($request->all(), [
'name' => 'required',
'client_addresses.*.address'=>'required',
'client_addresses.*.city'=>'required',
'client_addresses.*.state_province'=>'required',
'client_addresses.*.country'=>'required',
//Communication|
'client_communications.*.communication_type_id'=>'required|numeric',
//tag
'tags.*.tag_id'=>'required',
]);
foreach ($request->client_communications as $key=>$com) {
// dd($com);
if($com['communication_type_id']== "5")
{
$validator = Validator::make($request->all(), [
'client_communications.'.$key.'.communication_value' => 'required|numeric',
]);
}
if ($com['communication_type_id'] == "7"){
$validator = Validator::make($request->all(), [
'client_communications.'.$key.'.communication_value' => 'required|email',
]);
}
}
if ($validator->fails()) {
return response()->json(['errors'=>$validator->errors()]);
}
答案 0 :(得分:1)
您可以通过$ request变量获取发布的数据进行检查,如此
$validator = Validator::make($request->all(), [
'name' => 'required',
//address
'client_addresses.*.address'=>'required',
'client_addresses.*.city'=>'required',
'client_addresses.*.state_province'=>'required',
'client_addresses.*.country'=>'required',
'client_communications.*.communication_type_id'=>'required|numeric',
//client tag
'tags.*.tag_id'=>'required',
]);
if($request->communication_type_id == "4"){
$validator = Validator::make($request->all(), [
'client_communications.*.communication_value' => 'required|numeric|phone',
]);
}
if($request->communication_type_id == "7"){
$validator = Validator::make($request->all(), [
'client_communications.*.communication_value' => 'required|email',
]);
}
if ($validator->fails()) {
return response()->json(['errors'=>$validator->errors()]);
}
如果赞赏laravel验证的其他解决方案,否则这种方法应该很好。