Basics
Validation is as simple as in the FormRequests
classes provided by Laravel.
You can simply add rules to the rules()
method of the resource in the usual way.
namespace App\MoonShine\Resources; use MoonShine\Resources\ModelResource; class PostResource extends ModelResource{ //... public function rules($item): array { return [ 'title' => ['required', 'string', 'min:5'] ]; } //...}
![validation] (/storage/docs-assets/2.x/screenshots/validation.png)
Displaying validation errors
The $errorsAbove
resource parameter is responsible for displaying validation errors at the top of the form. The default value is true
, which means that validation errors will be displayed.
![errors_above_true] (/storage/docs-assets/2.x/screenshots/errors_above_true.png)
To hide validation errors at the top of the form, set the $errorsAbove
resource parameter to false
.
namespace App\MoonShine\Resources; use MoonShine\Resources\ModelResource; class PostResource extends ModelResource{ //... protected bool $errorsAbove = false; //...}
![errors_above_false] (/storage/docs-assets/2.x/screenshots/errors_above_false.png)
Messages
Using the validationMessages()
method, you can create your own validation error messages.
namespace App\MoonShine\Resources; use MoonShine\Resources\ModelResource; class PostResource extends ModelResource{ //... public function validationMessages(): array { return [ 'email.required' => 'Required email' ]; } //...}
Preparing Input For Validation
If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation()
method.
namespace App\MoonShine\Resources; use MoonShine\Resources\ModelResource; class PostResource extends ModelResource{ //... public function prepareForValidation(): void { request()?->merge([ 'email' => request() ?->string('email') ->lower() ->value() ]); } //...}