【问题标题】:Laravel Validate Field X if Field Y == "something"如果字段 Y == “某事”,Laravel 验证字段 X
【发布时间】:2021-04-20 05:12:49
【问题描述】:

我在 Laravel 中有一个表单,我需要帮助来验证字段。 该表单有 3 个文本字段和 1 个下拉按钮。 现在,仅当下拉菜单设置为特定值时,3 个文本字段中的 2 个才需要。

这是我的 3 个文本字段和下拉按钮代码:

<textarea class="form-control w-100 flex-fill instructions" id="instructions-1" name="instructions[]" rows="4" placeholder="Instructions"></textarea>
<button class="btn btn-secondary btn-md bg-white dropdown-toggle" type="button" data-toggle="dropdown" name="button[]" id="button-1" aria-haspopup="true" aria-expanded="false">Model</button>
<div class="dropdown-menu" aria-labelledby="button-1"><a class="dropdown-item" id="dropdown-item-model-1" href="#">Model</a><a class="dropdown-item" id="dropdown-item-engenius-1" href="#">Engenius</a>
<input type="text" class="text-body px-2 py-1 text" name="model[]" id="model-1" value="" placeholder="Enter Model" />
<input type="text" class="text-body px-2 py-1 text" name="pincode[]" id="pincode-1" value="" placeholder="Enter Pincode" />

这是我的验证码:

$validated = $request->validate([
        'button.*' => 'required',
        'instructions.*' => 'required|min:5',
        'model.*' => 'required_if:button.*,Model|min:5',
        'pincode.*' => 'required_if:button.*,Model|min:5',
    ]);

仅当下拉按钮具有值 Model 时,我才需要验证模型和 pincode 文本字段。 请帮忙。

【问题讨论】:

    标签: php laravel validation


    【解决方案1】:

    我能够找出问题所在。 我试图使用输入类型按钮的值进行验证,但表单发布不会发送按钮的值。 因此,我添加了一个隐藏的文本字段来保存下拉列表的值。 通过这种方式,我能够检查我的下拉菜单是否是模型,然后才需要文本字段模型和密码。

    以下是我的更新 HTML 代码:

    textarea class="form-control w-100 flex-fill instructions" id="instructions-1" name="instructions[]" rows="4" placeholder="Instructions"></textarea>
    <button class="btn btn-secondary btn-md bg-white dropdown-toggle" type="button" data-toggle="dropdown" name="button[]" id="button-1" aria-haspopup="true" aria-expanded="false">Model</button>
    <input type="hidden" name="job_type[]" id="job_type-1" value="Model" />
    <div class="dropdown-menu" aria-labelledby="button-1"><a class="dropdown-item" id="dropdown-item-model-1" href="#">Model</a><a class="dropdown-item" id="dropdown-item-engenius-1" href="#">Engenius</a>
    <input type="text" class="text-body px-2 py-1 text" name="model[]" id="model-1" value="" placeholder="Enter Model" />
    <input type="text" class="text-body px-2 py-1 text" name="pincode[]" id="pincode-1" value="" placeholder="Enter Pincode" />
    

    这是我更新的验证码:

        $validated = $request->validate([
            'job_type.*' => 'required',
            'instructions.*' => 'required|min:5',
            'model.*' => 'required_if:job_type.*,Model',
            'pincode.*' => 'required_if:job_type.*,Model',
        ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 2017-06-07
      • 2015-08-28
      • 2019-01-07
      • 2015-07-28
      • 2021-05-21
      • 2016-04-15
      相关资源
      最近更新 更多