我的有效载荷中有一个属性数组,如下所示:
{
"courier_code" : "shipadelivery",
"rule" : [
{
"attribute" : "day",
"operator" : "eq",
"value" : "tue"
}
],
"is_active" : true,
"priority" : 2
}
在这里我需要验证的是属性是否为day,则值应在['mon','tue','wed','thu','fri','sat','sun']
中,而运算符应为eq
我应该如何使用归因属性参数进行验证。我已经为此进行了验证,没有按照以下说明检查属性
$days = 'mon,tue,wed,thu,fri,sat,sun';
$rules = [
'courier_code' => 'required|exists:shipment_companies,code',
'is_active' => 'required|boolean',
'priority' => 'required|integer',
'rule' => 'required',
'rule.*.attribute' => 'required',
'rule.*.attribute' => 'required|in:'.$attributes,
'rule.*.value' => 'required',
'rule.*.operator' => 'required|in:'.$operators,
];
答案 0 :(得分:0)
您可以使用conditiosn将规则动态添加到规则数组中
use Illuminate\Validation\Rule;
$rules = [
'courier_code' => 'required|exists:shipment_companies,code',
'is_active' => 'required|boolean',
'priority' => 'required|integer',
'rule' => 'required',
'rule.*.attribute' => 'required',
'rule.*.operator' => [
'required',
Rule::in($operators),
],
];
if($request->filled('key-to-check') && $request->input('key-to-check') == 'day'){
$rules['rule.*.value'] = 'required|in:'.implode(',', $attributes);
}
由于是数组,您可以运行循环:
foreach($request->input('rule') as $key => $value){
$rule_key = 'rule.'.$key.'.value';
if($value['attribute'] == 'day'){
$rules[$rule_key] = 'required|in:'.$days;
}else{
$rules[$rule_key] = 'required';
}
}
希望这会有所帮助