在Laravel中编写自定义验证规则的一种方法是调用Artisan方法make:rule
:
php artisan make:rule EmptyIf
然后我不知道如何处理参数。"参数"的意思类似于require_if:foo,bar
.IlluminateContractsValidationRule
接口只有两个用于passes
函数的参数:
public function passes($attribute, $value);
所以我不明白我应该在哪里添加参数。我知道我可以通过服务提供商扩展验证器,就像这样:
Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
//
});
但这似乎是一种古老的方式,在我看来有点混乱。有没有办法在Rule
的函数passes
处理参数?
您可以为自定义规则定义构造函数,然后在自定义规则对象中传递参数。自定义规则:
class CustomRule implements Rule
{
private $params = [];
public function __construct($params)
{
$this->params = $params;
}
public function passes($attribute, $value)
{
return /*Here you can use $this->params*/;
}
}
验证:
$request->validate([
'input' => ['rule', new CustomRule(['param1','param2','paramN'])],
]);
我想做这样的事情:
protected $validationRules = [
'name' => 'required|myRule:a,b',
];
我从我的服务提供商book()方法中调用我的规则:
Validator::extend(
'myRule',
function ($attribute, $value, $parameters, $validator) {
$rule = new MyRule();
$rule->setA($parameters[0])
->setB($parameters[1]);
return $rule->passes($attribute, $value);
},
MyRule::errorMessage()
);
该规则如下所示:
use IlluminateContractsValidationRule;
/**
* Check if an encoded image string is a valid image
*/
class EncodedImage implements Rule
{
public function setA($a){}
public function setB($b){}
public function passes($attribute, $value)
{
return true;
}
public function message()
{
return self::errorMessage();
}
/**
* Static so the ServiceProvider can read it.
*/
public static function errorMessage()
{
return 'The :attribute is not valid';
}
}