Files
timebank-cc-public/app/Polls/Rules/RequiredWhenSelected.php
T

41 lines
1.0 KiB
PHP

<?php
namespace App\Polls\Rules;
use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Arr;
/**
* The field is required when the array at $listAttribute contains $key,
* e.g. the "Other" text when "Other" is one of the selected options.
*/
class RequiredWhenSelected implements ValidationRule, DataAwareRule
{
/** Run even when the field is empty. */
public bool $implicit = true;
private array $data = [];
public function __construct(private string $listAttribute, private string $key)
{
}
public function setData(array $data): static
{
$this->data = $data;
return $this;
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$selected = (array) Arr::get($this->data, $this->listAttribute, []);
if (in_array($this->key, $selected, true) && trim((string) $value) === '') {
$fail(__('validation.required', ['attribute' => __('Other')]));
}
}
}