Flexible DTO Documentation
Validation
Validation is performed on the input data before it is cast to the appropriate types. To make your DTO self-validating,
you must use the Mass6\FlexibleDTO\Validation\ValidatesProperties
trait in your DTO class. If validation fails,
an Illuminate\Validation\ValidationException
will be thrown.
Validation Rules
Validation rules are defined in the getRules()
method. This method should return an array of rules,
where the key is the name of the property and the value is the validation rule. Validation rules are defined
using Laravel validation rules.
use Mass6\FlexibleDTO\DTO;
use Mass6\FlexibleDTO\Validation\ValidatesProperties;
class MyDTO extends DataTransferObject
{
use ValidatesProperties;
protected function allowedProperties(): array
{
return [
'movie',
'releaseDate',
'rating',
];
}
protected function getRules(): array
{
return [
'movie' => 'required|string',
'releaseDate' => 'required|date',
'rating' => 'required|numeric',
];
}
}
Custom Validation Messages
Custom validation messages can be defined in the getMessages()
method. This method should return an array of messages,
where the key is the name of the property and the value is the validation message. Messages are defined using
Laravel validation messages syntax.
use Mass6\FlexibleDTO\DTO;
use Mass6\FlexibleDTO\Validation\ValidatesProperties;
class MyDTO extends DataTransferObject
{
use ValidatesProperties;
protected function allowedProperties(): array
{
return [
'movie',
'releaseDate',
'rating',
];
}
protected function getRules(): array
{
return [
'movie' => 'required|string',
'releaseDate' => 'required|date',
'rating' => 'required|numeric',
];
}
protected function getMessages(): array
{
return [
'movie.required' => 'The movie title is required.',
'releaseDate.required' => 'The release date is required.',
'rating.required' => 'The rating is required.',
];
}
}