Validation rules

# 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']
];
}
 
//...
}

# 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.

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;
//...
}

# 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()
]);
}
 
//...
}