64 lines
1.6 KiB
PHP
64 lines
1.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Rules;
|
|
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
use Illuminate\Support\Facades\Date;
|
|
|
|
class Adult implements ValidationRule
|
|
{
|
|
/** @param \Closure(string, ?string=):\Illuminate\Translation\PotentiallyTranslatedString $fail */
|
|
public function validate(string $attribute, mixed $value, \Closure $fail): void
|
|
{
|
|
if (! is_string($value)) {
|
|
$fail(trans('validation.custom.birth_date.date'));
|
|
|
|
return;
|
|
}
|
|
|
|
$format = match (true) {
|
|
$this->isSqlDate($value) => 'Y-m-d',
|
|
$this->isFormDate($value) => 'd/m/Y',
|
|
default => null,
|
|
};
|
|
|
|
if ($format === null) {
|
|
$fail(trans('validation.custom.birth_date.date'));
|
|
|
|
return;
|
|
}
|
|
|
|
$date = Date::createFromFormat($format, $value);
|
|
$majorityLimit = Date::now()->subYears(18);
|
|
|
|
if (! $date || ! $date->lessThanOrEqualTo($majorityLimit)) {
|
|
$fail(trans('validation.custom.birth_date.before_or_equal'));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if provided string is formatted for mysql
|
|
*/
|
|
private function isSqlDate(string $date): bool
|
|
{
|
|
if (preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $date)) {
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Check if provided string is formatted DD/MM/AAAA
|
|
*/
|
|
private function isFormDate(string $date): bool
|
|
{
|
|
if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}$/", $date)) {
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|