如果我有一个实现MyCustomRule
的自定义规则类(Illuminate\Contracts\Validation\Rule
),有没有一种快速的方法为规则注册别名,以便可以将其称为字符串?例如
public function rules()
{
return [
'email' => 'required|my_custom_rule'
];
}
我不想在AppServiceProvider
中重复自己。
答案 0 :(得分:3)
在我的自定义规则中,我添加了一个返回别名的__toString()
方法。我还允许将可选的$parameters
和$validator
传递给passes
方法。
使用Illuminate \ Contracts \ Validation \ Rule;
class MyCustomRule implements Rule
{
protected $alias = 'my_custom_rule';
public function __toString()
{
return $this->alias;
}
public function passes($attribute, $value, $parameters = [], $validator = null)
{
// put your validation logic here
return true;
}
public function message()
{
return 'Please enter a valid email address';
}
}
然后,我在AppServiceProvider中创建了一个方法,以同时使用其别名注册所有规则。
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
protected $rules = [
\App\Rules\MyCustomRule::class,
// ... other rules here
];
public function boot()
{
$this->registerValidationRules();
// ... do other stuff here
}
private function registerValidationRules()
{
foreach($this->rules as $class ) {
$alias = (new $class)->__toString();
if ($alias) {
Validator::extend($alias, $class .'@passes');
}
}
}
}