如何在Laravel中创建自定义验证器?

13

我需要创建一个扩展了Illuminate\Validation\Validator的自定义验证器。

我已经阅读了这里提供的一个答案中的示例:Laravel 4中的自定义验证

但问题是它没有清晰地展示如何使用自定义验证器。它没有显式地调用自定义验证器。您能否给我一个调用自定义验证器的示例。


这是一个自定义验证规则的示例,用于检查复合唯一列 - Bogdan
2个回答

17

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

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

php artisan make:rule GreaterThanTen

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

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

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

定义了自定义规则后,您可以在控制器验证中像这样使用它:

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

这种方式比旧的在 AppServiceProvider 类中创建 Closures 的方式要好得多。


1
我知道这是一个相当旧的答案,但我是 Laravel 新手,需要澄清一下:我看到的大多数示例都在控制器操作中展示了基本用法。如果我正在使用表单请求,那么上面的示例是否可以在 rules() 函数中工作,例如 return ['age' => 'greaterthanten']; - cautionbug
2
@cautionbug,是的,你可以在表单请求类中使用CV,只需使用以下代码导入新的自定义验证规则类:use App\Rules\GreaterThanTen; - Hemerson Varela
['required', new GreaterThanTen] 不起作用,请改用 [$request,new GreaterThanTen]。 - Fernando Torres

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

然后将规则添加到您的验证规则中。
$rules = array(
     'field_1'  => 'custom_rule_name:parameter'
);

这个在 Laravel 9 中似乎不再起作用了。我不知道这个功能是什么时候被移除的。 - NicoHood
这在 Laravel 9 中仍然有效。我从 Laravel 5 升级到 9.x,没有任何问题。 - le hien

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接