Php 如何在FormRequest中添加自定义验证程序?

Php 如何在FormRequest中添加自定义验证程序?,php,laravel,laravel-5,Php,Laravel,Laravel 5,我有一个规则(foobar),它不是内置在我想要在扩展的FormRequest中使用的Laravel中。如何为该特定规则创建自定义验证器 public function rules() { return [ 'id' => ['required', 'foobar'] ]; } 我知道存在Validator::extend,但我不想使用facades。我希望它“内置”到我的FormRequest。我如何做到这一点?甚至可能吗?可以通过为类创建验证程序属性并

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

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

我知道存在
Validator::extend
,但我不想使用facades。我希望它“内置”到我的
FormRequest
。我如何做到这一点?甚至可能吗?

可以通过为类创建
验证程序
属性并将其设置为
应用程序(“验证程序”)
来实现自定义验证方法。然后,您可以使用该属性运行
extend
,就像使用facade一样

public function validateFoobar($validator) {
    $validator->extend('foobar', function($attribute, $value, $parameters) {
        return ! MyModel::where('foobar', $value)->exists();
    });
}
创建
\u构造
方法并添加以下内容:

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

    $this->validateFoobar($this->validator);
}
然后创建一个名为
validatefobar
的新方法,该方法将
validator
属性作为第一个参数,并在该属性上运行
extend
,就像facade一样

public function validateFoobar($validator) {
    $validator->extend('foobar', function($attribute, $value, $parameters) {
        return ! MyModel::where('foobar', $value)->exists();
    });
}
有关扩展的更多详细信息,请参见

最后,您的
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();
        });
    }
}

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


如何执行此操作,并为新的验证筛选器生成自定义错误消息?@JimRubenstein:您可以将自定义消息放入
/resources/lang/de/validation.php
中,如下所示:
@JimRubenstein,您可以在FormRequest中使用此方法。请参阅我的更新答案以获取示例。@Marwelln经过一些研究,还有一个未记录的第三个参数,
Validator::extend
接受错误消息。不过,我更喜欢
FormRequest::messages
方法@roNn23我知道语言文件——这比我现在需要的抽象多了。谢谢