Laravel 7中required_if验证规则的正确设置——数组字段color_name与color_code的关联验证问题
解决数组字段的
required_if验证问题 你遇到的错误是因为required_if规则的语法要求至少两个参数:目标字段名和该字段需要匹配的值,你只传了字段名,所以触发了参数不足的报错。
针对你这种数组形式的输入(color_name[]和color_code[]),需要用数组通配符*来针对每一对对应的字段设置验证规则,这里有两种靠谱的方案:
方案1:使用required_if的完整语法
直接利用required_if的多参数写法,指定当对应索引的color_code不为空时,color_name必填:
$rules = [ 'color_code.*' => 'nullable', // 可选,先给color_code设置可空规则 'color_name.*' => 'required_if:color_code.*,!=,""' ];
这里的!=,""表示当color_code对应项的值不等于空字符串时,color_name必须填写。
方案2:使用闭包自定义验证(更灵活)
如果需要更复杂的判断逻辑,用闭包验证可以精准控制每一对字段的关联:
$rules = [ 'color_name.*' => function ($attribute, $value, $fail) { // 从字段名里提取数组索引,比如从"color_name.0"拿到索引0 $index = explode('.', $attribute)[1]; // 获取对应索引的color_code值 $correspondingCode = request()->input("color_code.$index"); // 判断:如果color_code不为空,但color_name为空,就抛出错误 if (!empty($correspondingCode) && empty(trim($value))) { $fail("The {$attribute} field is required when its corresponding color code is filled."); } }, 'color_code.*' => 'nullable' ];
两种方案都能实现你要的效果:当某一个color_code输入框有值时,对应的color_name必须填写;如果color_code是空的,color_name可以留空。
内容的提问来源于stack exchange,提问作者user15514832
相关产品推荐
相关产品推荐

