Custom rule based on another field - Good way or not ?

I'm implementing a custom rule that verify that two dates are in the same year. Custom Laravel Rule
final class SameYearAs implements ValidationRule
{
public function __construct(private mixed $toCompareWith)
{}

public function validate(string $attribute, mixed $value, Closure $fail): void
{
$toCompareWith = $this->toCompareWith;
if (filled($toCompareWith)) {
$value = CarbonImmutable::parse($value);
$toCompareWith = CarbonImmutable::parse($toCompareWith);

if (!$value->isSameYear($toCompareWith)) {
$fail('Not similar year!');
}
}
}
}
final class SameYearAs implements ValidationRule
{
public function __construct(private mixed $toCompareWith)
{}

public function validate(string $attribute, mixed $value, Closure $fail): void
{
$toCompareWith = $this->toCompareWith;
if (filled($toCompareWith)) {
$value = CarbonImmutable::parse($value);
$toCompareWith = CarbonImmutable::parse($toCompareWith);

if (!$value->isSameYear($toCompareWith)) {
$fail('Not similar year!');
}
}
}
}
Filament Form schema()
Forms\Components\DatePicker::make('start_at')
->label(__('Start at'))
->beforeOrEqual('end_at')
->required(),
Forms\Components\DatePicker::make('end_at')
->label(__('End at'))
->afterOrEqual('start_at')
->rules(fn (Get $get) => [new SameYearAs($get('start_at'))])
->required(),
Forms\Components\DatePicker::make('start_at')
->label(__('Start at'))
->beforeOrEqual('end_at')
->required(),
Forms\Components\DatePicker::make('end_at')
->label(__('End at'))
->afterOrEqual('start_at')
->rules(fn (Get $get) => [new SameYearAs($get('start_at'))])
->required(),
It works, but is that right do it like that ? I started using DataAwareRule but the problem is that the form data are stored in a "sub-array" and therefore if I use $this->data['data']['field-name'] the rule will works with Filament (Livewire?) but not in another classic class like a Controller.
array:19 [
"data" => array:34 []
"previousUrl" => "http://admin.nanou.test/admin/missions"
"mountedActions" => []
"mountedActionsArguments" => []
"mountedActionsData" => []
"defaultAction" => null
"defaultActionArguments" => null
"componentFileAttachments" => []
"mountedFormComponentActions" => []
"mountedFormXXXX"...
"activeRelationManager" => "2"
"record" => array:29 []
"savedDataHash" => null
]
array:19 [
"data" => array:34 []
"previousUrl" => "http://admin.nanou.test/admin/missions"
"mountedActions" => []
"mountedActionsArguments" => []
"mountedActionsData" => []
"defaultAction" => null
"defaultActionArguments" => null
"componentFileAttachments" => []
"mountedFormComponentActions" => []
"mountedFormXXXX"...
"activeRelationManager" => "2"
"record" => array:29 []
"savedDataHash" => null
]
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server