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');
}
}
}
}