我需要创建一个扩展了Illuminate\Validation\Validator
的自定义验证器。
我已经阅读了这里提供的一个答案中的示例:Laravel 4中的自定义验证
但问题是它没有清晰地展示如何使用自定义验证器。它没有显式地调用自定义验证器。您能否给我一个调用自定义验证器的示例。
我需要创建一个扩展了Illuminate\Validation\Validator
的自定义验证器。
我已经阅读了这里提供的一个答案中的示例:Laravel 4中的自定义验证
但问题是它没有清晰地展示如何使用自定义验证器。它没有显式地调用自定义验证器。您能否给我一个调用自定义验证器的示例。
在 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
的方式要好得多。
rules()
函数中工作,例如 return ['age' => 'greaterthanten'];
? - cautionbuguse App\Rules\GreaterThanTen
; - Hemerson Varela我不知道这是否符合您的要求,但要设置自定义规则,您首先需要扩展自定义规则。
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'
);