【发布时间】:2020-07-16 01:52:22
【问题描述】:
我有一个复选框列表,例如
[] Tomatoes
[] Cucumbers
[] Pumpkins
[] Other
当您选中Other 时,会弹出一个文本字段。这将作为 JSON 字符串存储在单个列 vegetables 中。
FormRequest.php
public function rules()
{
return [
'vegetable' => 'required'
]
}
form.html
<legend class="@error('diagnose') text-red-500 : text-gray-900 @enderror">
Did you get any of the following diagnoses last week? *
</legend>
<form action="" method="post">
<input name="vegetable[]" type="checkbox" value="Tomatoes">Tomatoes</input>
<input name="vegetable[]" type="checkbox" value="Cucumbers">Cucumbers</input>
<input name="vegetable[]" type="checkbox" value="Pumpkins">Pumpkins</input>
<input name="vegetable[]" type="checkbox" value="Other">Other</input>
<input name="???" type="text"></input>
</form>
我们的想法是以这种方式命名最后一个字段,因此很容易:
- 显示验证错误,最好不要检查两个字段(例如
vegetable和vegetable_other) - 将它的价值添加到 JSON 中,而不需要太多
ifs。
如何在 Laravel 中做到这一点而不创建代码墙?
【问题讨论】:
-
您应该提供一些代码,至少是这些选项的 HTML 以及您将数据发送到服务器的方法。这应该是一个简单的答案,但我会对您的代码做出太多假设。同时,请查看此验证规则:laravel.com/docs/7.x/validation#rule-required-if
-
为了清楚起见,我稍微编辑了我的代码
-
昨天没来得及看更新,看了一下这个问题:stackoverflow.com/questions/43147584/…既然是数组,看来得用组合规则了。
标签: laravel laravel-validation laravel-7