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

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

问题描述:

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

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

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

I have read an example given in an answer here: Custom validation in 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.

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

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

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

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

php artisan make:rule GreaterThanTen

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

laravel will place the new rule class in the app/Rules directory

自定义对象验证规则的示例可能类似于:

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

这种方法比在AppServiceProvider类上创建Closures的旧方法好得多

This way is much better than the old way of create Closures on the AppServiceProvider Class