首页 > 解决方案 > 仅当值不可用时才需要验证

问题描述

我有以下代码:

{!! Form::select('the_selection', ['' => 'Nothing', 'Foo' => 'Bar']) !!}

以及以下内容:

<input class="input" name="the_other_field" type="text"/>

仅当不是the_other_field时才需要该字段。the_selection''

所以我尝试了tis验证:

$this->validate($request, [
    // 'recurring'        => 'required|nullable',
    'the_other_field'      => 'required_without:the_selection,|date_format:Y-m-d|after:today',
]);

但这不起作用..

标签: laravellaravel-5

解决方案


如果您将验证移至表单请求,则可以添加“有时”验证规则:

class YourRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'the_selection' => 'required',
        ];
    }

    public function withValidator($validator)
    {
        $validator->sometimes('the_other_field', 'required', function ($input) {
            return $input->the_selection != '';
        });
    }
}

推荐阅读