F
Filament16mo ago
azhihao

How to do complex validation on a modal form?

For example, there're 3 integer fields of which the sum should not exceed the number in 4th field? Illuminate\Contracts\Validation\ValidationRule seems only validate on single attribute, how can I have a validation function that has complete filled data of the form? Thanks in advance.
5 Replies
toeknee
toeknee16mo ago
Not sure if it works, but I believe the principle is there.
->rules([
function () {
return function (string $attribute, $value, Closure $fail, Closure $get) {
if ((int)$value < ((int) $get('field1') + (int) $get('field2') + (int) $get('field3'))) {
$fail('Error, the 3 integer fields are greater than this field. ');
}
};
},
])
->rules([
function () {
return function (string $attribute, $value, Closure $fail, Closure $get) {
if ((int)$value < ((int) $get('field1') + (int) $get('field2') + (int) $get('field3'))) {
$fail('Error, the 3 integer fields are greater than this field. ');
}
};
},
])
azhihao
azhihaoOP16mo ago
Hi @toeknee thanks for the hint. Injecting $get should work, but seems a little hacky to me. I was wondering if there exists a validation hook before submitting the form...
toeknee
toeknee16mo ago
I doubt it tbh, you could build your own Laravel Validation where you pass in the values, but you are still getting an eclosure
azhihao
azhihaoOP16mo ago
I just found the HasLifecycleHooks concern, and looks like it suits my need. But still need to find a way to display validation errors since I cannot inject $fail in it's closure..
LeandroFerreira
LeandroFerreira16mo ago
if you want to display validation messages, you can use
throw ValidationException::withMessages([
$component->getStatePath() => 'error message',
]);
throw ValidationException::withMessages([
$component->getStatePath() => 'error message',
]);
Want results from more Discord servers?
Add your server