我正在使用Laravel 5.4,需要稍微特定的验证规则,但我认为这应该可以轻松实现,而不必扩展类。只是不确定如何使其工作...
我想做的是,如果program
数组包含'Music'
,则使'music_instrument'
表单字段为必填项。
我找到了这个帖子How to set require if value is chosen in another multiple choice field in validation of laravel?,但它并不是一个解决方案(因为一开始就没有解决),而且它不起作用的原因是提交的数组索引不是恒定的(未选中的复选框在索引提交结果时不被考虑...)
我的情况看起来像这样:
<form action="" method="post">
<fieldset>
<input name="program[]" value="Anthropology" type="checkbox">Anthropology
<input name="program[]" value="Biology" type="checkbox">Biology
<input name="program[]" value="Chemistry" type="checkbox">Chemistry
<input name="program[]" value="Music" type="checkbox">Music
<input name="program[]" value="Philosophy" type="checkbox">Philosophy
<input name="program[]" value="Zombies" type="checkbox">Zombies
<input name="music_instrument" type="text" value"">
<button type="submit">Submit</button>
</fieldset>
</form>
如果我从复选框列表中选择一些选项,这可能会在我的$request
值中产生此结果。[program] => Array
(
[0] => Anthropology
[1] => Biology
[2] => Music
[3] => Philosophy
)
[music_instrument] => 'Guitar'
在这里查看验证规则:https://laravel.com/docs/5.4/validation#available-validation-rules,我认为像这样的东西应该可以工作,但实际上我什么也没有得到:
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program,in:Music'
]);
我也希望这个能行,但没成功:
'music_instrument' => 'required_if:program,in_array:Music',
有想法吗?建议呢?
谢谢!