【发布时间】:2017-08-26 03:11:26
【问题描述】:
我在 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',
想法?有什么建议吗?
谢谢!
【问题讨论】:
标签: php laravel laravel-5 laravel-5.4 laravel-validation