Reputation: 5835
If I have a custom rule class (MyCustomRule
) implementing Illuminate\Contracts\Validation\Rule
, is there a quick way to register an alias for the rule so that I can call it as a string? e.g.
public function rules()
{
return [
'email' => 'required|my_custom_rule'
];
}
I don't want to repeat myself in the AppServiceProvider
.
Upvotes: 6
Views: 2089
Reputation: 5835
In my custom Rule, I added a __toString()
method which returns the alias. I also allowed optional $parameters
and $validator
to be passed to the passes
method.
use 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';
}
}
Then I created a method in AppServiceProvider to register all of the rules with their aliases at once.
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');
}
}
}
}
Upvotes: 12