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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36265166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:28:59  来源:igfitidea点击:

Laravel How to Make Custom Validator?

phplaravelvalidation

提问by NoName2

I need to make my own validator that extends Illuminate\Validation\Validator

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

I have read an example given in an answer here: Custom validation in Laravel 4

我已经阅读了此处的答案中给出的示例:Laravel 4 中的自定义验证

But the problem is it doesn't clearly show how to use the custom validator. It doesn't call the custom validator explicitly. Could you give me an example how to call the custom validator.

但问题是它没有清楚地显示如何使用自定义验证器。它不会显式调用自定义验证器。你能给我一个如何调用自定义验证器的例子。

回答by Hemerson Varela

After Laravel 5.5 you can create you own Custom Validation Rule object.

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

In order to create the new rule, just run the artisan command:

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

php artisan make:rule GreaterThanTen

laravel will place the new rule class in the app/Rulesdirectory

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

An example of a custom object validation rule might look something like:

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

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.';
    }
}

With the custom rule defined, you might use it in your controller validation like so:

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

public function store(Request $request)
{
    $request->validate([
        'age' => ['required', new GreaterThanTen],
    ]);
}

This way is much better than the old way of create Closureson the AppServiceProviderClass

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

回答by Carlos Salazar

I don't know if this is what you want but to set customs rules you must first you need to extend the custom rule.

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

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 
});

Then add the rule to your validation rules

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

$rules = array(
     'field_1'  => 'custom_rule_name:parameter'
);