Alias for custom validation rule in Laravel?
Asked Answered
A

1

6

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.

Agretha answered 13/3, 2020 at 12:57 Comment(0)
A
12

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');
            }
        }
    }
}
Agretha answered 13/3, 2020 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.