在之前的版本里,如果我们想创建自定义的数据验证规则,我们得使用Validator::extend
的方式,但是呢相关的代码不够集中——具体的规则得写在AppServiceProvider
中,而相应的error message则要写在语言文件中,比如resources/lang/en/validation.php
,更具体的可以看看5.4的文档
在5.5中,可以使用artisan command来生成自己的验证规则文件:
phpartisanmake:ruleCustomRule
这个class实现(implement)的是Rule
contract(interface),默认路径app/Rules/CustomRule.php
,我们看一下:
class CustomRule implements Rule
{
[...]
public function passes($attribute, $value)
{
return $value !== 'unwantedname';
}
public function message()
{
return 'You cannot use that as your username';
}
[...]
}
可以看到里面有两个方法,passes
方法接收两个参数attribute
和value
,返回的是boolean
。$attribute
就是要被验证的字段,而这个$value
就是该字段的实际值。比如上面的例子,就是让某个字段不能是某个特定的名字。
那么怎么来调用这个自定义规则呢?可以类似这样:
use App\Rules\CustomRule;
request()->validate([
'username' => [
'required',
new CustomRule()
],
'anotherfield' => 'required|min:5'
]);