【问题标题】:What's the best way to handle "Other" on a list of radio buttons or checkboxes在单选按钮或复选框列表上处理“其他”的最佳方法是什么
【发布时间】: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>

我们的想法是以这种方式命名最后一个字段,因此很容易:

  1. 显示验证错误,最好不要检查两个字段(例如vegetablevegetable_other
  2. 将它的价值添加到 JSON 中,而不需要太多 ifs。

如何在 Laravel 中做到这一点而不创建代码墙?

【问题讨论】:

  • 您应该提供一些代码,至少是这些选项的 HTML 以及您将数据发送到服务器的方法。这应该是一个简单的答案,但我会对您的代码做出太多假设。同时,请查看此验证规则:laravel.com/docs/7.x/validation#rule-required-if
  • 为了清楚起见,我稍微编辑了我的代码
  • 昨天没来得及看更新,看了一下这个问题:stackoverflow.com/questions/43147584/…既然是数组,看来得用组合规则了。

标签: laravel laravel-validation laravel-7


【解决方案1】:

你可以这样做 验证蔬菜是否是其他的

 public function rules()
    {
        return [
             'vegetable' => 'required',
             'vegetableName'=>'required_if:vegetable,Other'     
        ]
    }

在形式上

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="vegetableName" type="text"></input>
</form>

【讨论】:

  • 但是由于这些是复选框蔬菜是一个数组,所以required_if 不会工作?
  • 你可以像这样为输入标签添加多个属性 Tomatoes
猜你喜欢
  • 1970-01-01
  • 2013-12-10
  • 2012-04-12
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 2010-09-24
相关资源
最近更新 更多