Laravel 在 FormRequest 中使用复杂的条件验证规则

Using complex conditional validation rule in FormRequest in Laravel

我正在使用 Laravel 开发 Web 应用程序。我现在正在做的是为验证创建一个 FirmRequest。

这是我的表单请求。

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules()
    {
        return [
            'title' => 'required',
            'type' => 'required',
            'complex_field' => ...need complex conditional validation based on the type field
        ];
    }
}

如果我没有使用 FormRequest,我可以在控制器中创建验证器并像这样设置复杂的条件验证规则。

$v = Validator::make($data, [
    //fields and rules
]);

$v->sometimes('reason', 'required|max:500', function ($input) {
    return $input->games >= 100;
});

但问题是我没有在控制器中创建验证器。但我正在使用 FormRequest。我怎样才能在 FormRequest 中实现相同的功能?

您可以根据输入数据手动调整规则:

class StoreVacancy extends FormRequest
{
    public function rules()
    {
        $reason = $this->request->get('reason'); // Get the input value
        $rules = [
            'title' => 'required',
            'type'  => 'required',
        ];

        // Check condition to apply proper rules
        if ($reason >= 100) {
            $rules['complex_field'] = 'required|max:500';
        }

        return $rules;
    }
}

它与有时不一样,但它做同样的工作。

您可以查看https://github.com/laravel/framework/blob/5.7/src/Illuminate/Foundation/Http/FormRequest.php中的createDefaultValidator函数。我们将覆盖该函数并添加我们的条件

    /**
     * Add Complex Conditional Validation to the validator instance.
     *
     * @param  \Illuminate\Validation\Factory  $factory
     * @return \Illuminate\Validation\Validator
     */
    public function validator($factory)
    {
        $validator = $factory->make(
            $this->validationData(),
            $this->container->call([$this, 'rules']),
            $this->messages(),
            $this->attributes()
        );

        $validator->sometimes('reason', 'required|max:500', function ($input) {
            return $input->games >= 100;
        });

        return $validator;
    }

从 5.4 开始,您可以在 FormRequest 中使用方法“withValidator”: https://laravel.com/docs/5.4/validation

This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are actually evaluated

use Illuminate\Foundation\Http\FormRequest;

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

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

    public function withValidator($validator)
    {
        $validator->sometimes('reason', 'required|max:500', function ($input) {
            return $input->games >= 100;
        });
    }
}