Ad
Alias For Custom Validation Rule In Laravel?
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
.
Ad
Answer
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');
}
}
}
}
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad