Laravel如何制作自定义验证器?

NoN*_*me2 7 php validation laravel

我需要制作我自己的扩展验证器 Illuminate\Validation\Validator

我在这里的答案中读到了一个例子:Laravel 4中的自定义验证

但问题是它没有清楚地显示如何使用自定义验证器.它不会显式调用自定义验证程序.你能举个例子来说明如何调用自定义验证器吗?

Car*_*zar 8

我不知道这是否是您想要的,但要设置海关规则,您必须首先需要扩展自定义规则。

Validator::extend('custom_rule_name',function($attribute, $value, $parameters){
     //code that would validate
     //attribute its the field under validation
     //values its the value of the field
     //parameters its the value that it will validate againts 
});
Run Code Online (Sandbox Code Playgroud)

然后将该规则添加到您的验证规则中

$rules = array(
     'field_1'  => 'custom_rule_name:parameter'
);
Run Code Online (Sandbox Code Playgroud)


Hem*_*ela 7

在 Laravel 5.5 之后,您可以创建自己的自定义验证规则对象。

为了创建新规则,只需运行 artisan 命令:

php artisan make:rule GreaterThanTen
Run Code Online (Sandbox Code Playgroud)

laravel 会将新的规则类放在app/Rules目录中

自定义对象验证规则的示例可能如下所示:

php artisan make:rule GreaterThanTen
Run Code Online (Sandbox Code Playgroud)

定义自定义规则后,您可以在控制器验证中使用它,如下所示:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class GreaterThanTen implements Rule
{
    // Should return true or false depending on whether the attribute value is valid or not.
    public function passes($attribute, $value)
    {
        return $value > 10;
    }

    // This method should return the validation error message that should be used when validation fails
    public function message()
    {
        return 'The :attribute must be greater than 10.';
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方式比ClosuresAppServiceProviderClass上创建的旧方式要好得多

  • @cautionbug,是的,您可以在表单请求类中使用 CV,您只需使用以下命令导入新的自定义验证规则类:`use App\Rules\GreaterThanTen`; (2认同)