Validation
Adding validation to fields.
Fields
You can add validation to your fields:
Text::make(__('Name'), 'name')
->rules('required', 'min:3')
If validation only needs to happen when creating the resource:
Text::make(__('Name'), 'name')
->createRules('required', Rule::unique('examples', 'name'))
Or only when updating:
Text::make(__('Name'), 'name')
->editRules(function(\App\Models\Tenant\Example $example) {
return [
'required', 'max:5'
];
}),
Validate multiple/array
By default, fields like BelongsToMany
receive an array of values which you can validate like this:
BelongsToMany::make(__('Tenants'), 'tenants', Tenant::class)
->rules('required', 'array', Rule::exists(TenantModel::class, 'id'))
Custom validation
Sometimes you need to validate with a closure. This is possible with the following syntax:
Text::make(__('Name'), 'name')
->rules(
function ($attribute, $value, $fail) {
if ($value === 'test') {
return true;
}
return $fail(__('My message'));
}
),
Fully customizing validation
Sometimes you need to conditionally validate multiple values in an array. Or validate an array with a key-value pair. You can achieve this by creating a custom field and overriding the following method on the field:
public function applyToValidatorRules($rules, ?Model $model = null, array $state = []): array
{
$nullable = !$this->isRequired($model, $state);
$rules["$this->name.country_code"] = [$nullable ? 'nullable' : 'required', 'min:2', 'max:2'];
$rules["$this->name.number"] = [$nullable ? 'nullable' : 'required'];
if (!$nullable || (request($this->name)['input'] ?? '') !== '') {
$rules["$this->name.valid"] = ['required', 'in:1'];
}
return $rules;
}
You can then also override the translations for each attribute:
public function getValidationAttributes(): array
{
return [
$this->name . '.input' => __('Number'),
$this->name . '.country_code' => __('Country'),
$this->name . '.country_calling_code' => __('Country'),
$this->name . '.national_number' => __('Number'),
$this->name . '.number' => __('Number'),
$this->name . '.valid' => __('Number'),
];
}
If needed, you can also customize the messages:
public function getValidationMessages(): array
{
return [
$this->name . '.addresses.*.email' => __('mailing::mailing.One of the addresses is not valid'),
$this->name . '.addresses.required' => __('mailing::mailing.At least one address is required'),
];
}
Docs for creating a field: Creating a field
Global attributes and messages
If you want to append validation attributes and messages without having to extend a Field
class, you can also add the folllowing methods on your resource.