Laravel Livewire Volt:如何优化数组关联属性的必填验证(无需自定义验证器)
Laravel Livewire Volt 实现数组包含特定值时字段必填的验证优化
可行方案(无需自定义验证器)
方案1:使用闭包验证规则
直接在字段的规则数组中添加自定义闭包,判断数组是否包含'other'且字段为空:
use Livewire\Volt\Component; new class extends Component { public array $additionalDanceGenres = []; public string $otherAdditionalDanceGenre = ''; public function rules(): array { return [ 'additionalDanceGenres' => 'array', 'otherAdditionalDanceGenre' => [ 'string', function ($attribute, $value, $fail) { if (in_array('other', $this->additionalDanceGenres) && trim($value) === '') { $fail('请填写其他舞蹈类型'); } }, ], ]; } };
闭包内可以安全访问$this,因为它是在验证触发时才执行,处于组件的对象上下文之中。
方案2:利用Rule::requiredIf的闭包形式
这是更简洁的写法,将判断逻辑包裹在闭包里传递给Rule::requiredIf,避免直接使用$this导致的上下文错误:
use Livewire\Volt\Component; use Illuminate\Validation\Rule; new class extends Component { public array $additionalDanceGenres = []; public string $otherAdditionalDanceGenre = ''; public function rules(): array { return [ 'additionalDanceGenres' => 'array', 'otherAdditionalDanceGenre' => [ 'string', Rule::requiredIf(fn () => in_array('other', $this->additionalDanceGenres)), ], ]; } };
为什么之前的写法无效?
- 规则字符串
required_if:additionalDanceGenres.*,other不生效:required_if的第一个参数需要是单个字段名,additionalDanceGenres.*是数组元素的通配符写法,Laravel验证器无法以此作为条件判断的依据。 - 直接使用
Rule::requiredIf(in_array('other', $this->additionalDanceGenres))报错:这个表达式在rules()方法返回数组时就会执行,此时组件的对象上下文尚未完全就绪,导致Using $this when not in object context错误。而闭包形式会延迟到验证执行时才计算条件,此时$this是有效的。
内容的提问来源于stack exchange,提问作者Luciano
相关产品推荐
相关产品推荐

