如何在FormRequest中添加自定义验证器?

时间:2014-10-28 18:38:56

标签: php laravel laravel-5

我有一个规则(foobar)没有内置在Laravel中我想在扩展的FormRequest中使用。如何为该特定规则创建自定义验证器?

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

我知道Validator::extend存在,但我不想使用外墙。我想要它"内置"到我的FormRequest。我该怎么做,甚至可能吗?

2 个答案:

答案 0 :(得分:4)

可以通过为您的班级创建validator属性并将其设置为app('validator')来获得自定义验证方法。然后,您可以使用该属性运行extend,就像使用外观一样。

创建__construct方法并添加:

public function __construct() {
    $this->validator = app('validator');

    $this->validateFoobar($this->validator);
}

然后创建一个名为validateFoobar的新方法,该方法将validator属性作为第一个参数并在其上运行extend,就像使用外观一样。

public function validateFoobar($validator) {
    $validator->extend('foobar', function($attribute, $value, $parameters) {
        return ! MyModel::where('foobar', $value)->exists();
    });
}

有关extend的详细信息,请here

最后,您的FormRequest可能如下所示:

<?php namespace App\Http\Requests;

use App\Models\MyModel;
use App\Illuminate\Foundation\Http\FormRequest;

class MyFormRequest extends FormRequest {
    public function __construct() {
        $this->validator = app('validator');

        $this->validateFoobar($this->validator);
    }

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

    public function messages() {
        return [
            'id.required' => 'You have to have an ID.',
            'id.foobar' => 'You have to set the foobar value.'
        ];
    }

    public function authorize() { return true; }

    public function validateFoobar($validator) {
        $validator->extend('foobar', function($attribute, $value, $parameters) {
            return ! MyModel::where('category_id', $value)->exists();
        });
    }
}

答案 1 :(得分:0)

从 5.4 版开始,您可以使用 withValidator 方法来扩展规则。

<?php namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MyFormRequest extends FormRequest
{

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

    public function messages() {
        return [
            'id.required' => 'You have to have an ID.',
            'id.foobar' => 'You have to set the foobar value.'
        ];
    }

    public function withValidator($validator)
    {
        $validator->addExtension('foobar', function ($attribute, $value, $parameters, $validator) {
            return ! MyModel::where('category_id', $value)->exists();
        });
    }
}
相关问题