z-song / laravel-admin

Build a full-featured administrative interface in ten minutes
https://laravel-admin.org
MIT License
11.15k stars 2.82k forks source link

How to create custom validation rules? #5731

Open r-shaygan opened 1 year ago

r-shaygan commented 1 year ago

by Encore\Admin\Form\Field::rules method, we can just pass a string or closure that returns a string of predefined rules. but I need to create my own rules as a closure (like laravel does)

alexoleynik0 commented 1 year ago

It accepts an array of rules too, Laravel-like. So something like:

$form->text('seo_slug', __('SEO slug'))->rules([
    'min:3',
    new Slug(), // <-- custom validation rule
    'unique:pages,seo_slug',
]);
r-shaygan commented 1 year ago

It accepts an array of rules too, Laravel-like. So something like:

$form->text('seo_slug', __('SEO slug'))->rules([
    'min:3',
    new Slug(), // <-- custom validation rule
    'unique:pages,seo_slug',
]);

I know it accepts an array but every element of the array should return a string of predefined rules. in your example, what does the method of Slug return??
can you write a closure rule as an example?

alexoleynik0 commented 1 year ago

new Slug() returns a new instance of Validation Rule extended class, as described by Laravel docs of the version you use. I was using docs 8.x example.