自定义验证规则 (Laravel 5.5 新功能早知道)
Laravel 5.5 的新功能 —— 添加自定义验证规则,以下是 Taylor 写的一个快速入门教程。
定义规则
假设有段程序需要验证给定的 GitHub 仓库和分支是否存在,而唯一的方法是对 GitHub 进行 API 调用。 那么,封装使用这个自定义的验证规则的方式是最适合不过了。
首先,我们简单地定义一个类,写两个方法:passes
和 message
。 然后把这个类放在命名空间 App\Rules
中:
<?php
namespace App\Rules;
use App\Source;
use Illuminate\Contracts\Validation\Rule;
class ValidRepository implements Rule
{
/**
* The source control provider instance.
*
* @var \App\Source
*/
public $source;
/**
* The branch name.
*
* @var string
*/
public $branch;
/**
* Create a new rule instance.
*
* @param \App\Source $source
* @param string $branch
* @return void
*/
public function __construct($source, $branch)
{
$this->source = $source;
$this->branch = $branch;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
if (! $this->source instanceof Source) {
return false;
}
return $this->source->client()->validRepository(
$value, $this->branch
);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The given repository is invalid.';
}
}
这段代码中, passes
方法将从 Laravel 的验证器接收 $attribute
和 $value
参数。 $attribute
是要验证的字段的名称,而 $value
是该字段的值。 这个方法只需要判断给定的值来返回 true
或 false
。
在上面的例子中,Source
对象是一个 Eloquent
模型,代表一个源码控制提供器,如 GitHub。
message
方法应返回验证失败时的错误消息。 在这个方法中,自由发挥的空间还是挺多的,比如可以从翻译文件中检索一个字符串。
使用规则
当自定义验证规则完成定义之后,就可以在 Request 中使用它了。Laravel 5.5 中可以直接从 Request 对象中获取 validate
方法,在规则数组中实例化我们的自定义规则:
<?php
use App\Rules\ValidRepository;
$request->validate([
'repository' => [
'required',
new ValidRepository($this->source(), $request->branch)
]
]);
你还可以在其他地方比如表单请求或执行验证时使用自定义规则。
这个新功能提供了一种快速、简单的方法来定义自定义验证规则,一起期待 Laravel 5.5 的到来~
参考链接:https://medium.com/@taylorotwell/custom-va... 、
https://laravel-news.com/laravel-5-5-custo...
本作品采用《CC 协议》,转载必须注明作者和本文链接
:+1:
这个好