30 lines
806 B
PHP
30 lines
806 B
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Rules;
|
|
|
|
use Closure;
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
|
|
/**
|
|
* Validate a date in the format YYYY-MM-DD HH:MM:SS
|
|
*/
|
|
class DateYMDHIS implements ValidationRule
|
|
{
|
|
public function validate(string $attribute, mixed $value, Closure $fail): void
|
|
{
|
|
if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $value)) {
|
|
$fail('validation.date_ymdhis');
|
|
}
|
|
if (\DateTimeImmutable::createFromFormat("Y-m-d H:i:s", $value) === false) {
|
|
$fail('validation.date_ymdhis');
|
|
}
|
|
// DateTime accept dates such as 2021-31-55
|
|
$errors = \DateTimeImmutable::getLastErrors();
|
|
if (!empty($errors['warning_count'])) {
|
|
$fail('validation.date_ymdhi');
|
|
}
|
|
}
|
|
}
|