仅当下拉值为 'other' 时才验证 'other' 字段

Validating 'other' field only if dropdown value is 'other'

解释起来有点复杂,但是一个非常常见的用例。

我的页面上有这个字段:

<select class="form-control" name="how_you_heard_about_us" id="select-hearaboutus">

其中的所有选项都有名称,包括这个:

<option value="Other">Other</option>

我还有一个文本输入,只有在用户选择 'Other' 时才需要。

这是我的压缩验证码:

$this->validate($request, [
    'first_name' => 'required|max:20',
    'last_name' => 'required|max:20',
    'how_you_heard_about_us' => 'required'
]);

我正在尝试进行设置,如果下拉列表设置为 'other'。

,则用户只需输入文本字段

如何在 Laravel 5.2 中有条件地要求自由文本字段?

您正在查找 required_if 规则:

'your_text_field' => 'required_if:how_you_heard_about_us,Other'