From 5fe4b96ebf651407d6b8ba2272e4bdab980b4438 Mon Sep 17 00:00:00 2001 From: Alexandre Gomes Gaigalas Date: Sun, 19 Feb 2023 14:57:48 -0300 Subject: [PATCH] Stricter date format validation --- library/Helpers/CanValidateDateTime.php | 18 +++++++++++++++++- tests/unit/Rules/DateTimeTest.php | 1 + 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/library/Helpers/CanValidateDateTime.php b/library/Helpers/CanValidateDateTime.php index d2ec4b84..306f4195 100644 --- a/library/Helpers/CanValidateDateTime.php +++ b/library/Helpers/CanValidateDateTime.php @@ -9,7 +9,11 @@ declare(strict_types=1); namespace Respect\Validation\Helpers; +use DateTime; +use DateTimeZone; + use function checkdate; +use function date_default_timezone_get; use function date_parse_from_format; use function preg_match; @@ -30,13 +34,25 @@ trait CanValidateDateTime 'r' => 'D, d M Y H:i:s O', ]; - $info = date_parse_from_format($exceptionalFormats[$format] ?? $format, $value); + $format = $exceptionalFormats[$format] ?? $format; + + $info = date_parse_from_format($format, $value); if (!$this->isDateTimeParsable($info)) { return false; } if ($this->isDateFormat($format)) { + $formattedDate = DateTime::createFromFormat( + $format, + $value, + new DateTimeZone(date_default_timezone_get()) + ); + + if ($formattedDate === false || $value !== $formattedDate->format($format)) { + return false; + } + return $this->isDateInformation($info); } diff --git a/tests/unit/Rules/DateTimeTest.php b/tests/unit/Rules/DateTimeTest.php index 6de48e36..bb9a1361 100644 --- a/tests/unit/Rules/DateTimeTest.php +++ b/tests/unit/Rules/DateTimeTest.php @@ -72,6 +72,7 @@ final class DateTimeTest extends RuleTestCase [new DateTime('h'), 24], [new DateTime('c'), new DateTimeMutable()], [new DateTime('c'), new DateTimeImmutable()], + [new DateTime('Y-m-d H:i:s'), '21-3-123:12:01'], ]; }