diff --git a/src/Forms/Controls/DateTimeControl.php b/src/Forms/Controls/DateTimeControl.php index 72732b6d3..f44d77060 100644 --- a/src/Forms/Controls/DateTimeControl.php +++ b/src/Forms/Controls/DateTimeControl.php @@ -69,7 +69,9 @@ public function setFormat(string $format) */ public function setValue($value) { - $this->value = $value === null ? null : $this->normalizeValue($value); + $this->value = $value === null || $value === '' + ? null + : $this->normalizeValue($value); return $this; } @@ -96,7 +98,7 @@ private function normalizeValue($value): \DateTimeImmutable { if (is_numeric($value)) { $dt = (new \DateTimeImmutable)->setTimestamp((int) $value); - } elseif (is_string($value)) { + } elseif (is_string($value) && $value !== '') { $dt = new \DateTimeImmutable($value); // createFromFormat() must not be used because it allows invalid values } elseif ($value instanceof \DateTime) { $dt = \DateTimeImmutable::createFromMutable($value); @@ -121,7 +123,7 @@ public function loadHttpData(): void { $value = $this->getHttpData(Nette\Forms\Form::DataText); try { - $this->value = is_string($value) && preg_match('~^(\d{4}-\d{2}-\d{2})?T?(\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?$~', $value) + $this->value = is_string($value) && preg_match('~^[\dT.:-]+$~', $value) ? $this->normalizeValue($value) : null; } catch (\Throwable $e) { diff --git a/tests/Forms/Controls.DateTimeControl.loadData.phpt b/tests/Forms/Controls.DateTimeControl.loadData.phpt index 26eb3c936..a5236bf07 100644 --- a/tests/Forms/Controls.DateTimeControl.loadData.phpt +++ b/tests/Forms/Controls.DateTimeControl.loadData.phpt @@ -65,6 +65,33 @@ test('invalid time', function () { }); +test('empty date', function () { + $_POST = ['date' => '']; + $form = new Form; + $input = $form->addDate('date'); + Assert::null($input->getValue()); + Assert::false($input->isFilled()); +}); + + +test('empty time', function () { + $_POST = ['time' => '']; + $form = new Form; + $input = $form->addTime('time'); + Assert::null($input->getValue()); + Assert::false($input->isFilled()); +}); + + +test('empty date-time', function () { + $_POST = ['date' => '']; + $form = new Form; + $input = $form->addDateTime('date'); + Assert::null($input->getValue()); + Assert::false($input->isFilled()); +}); + + test('valid date', function () { $_POST = ['date' => '2023-10-22']; $form = new Form; diff --git a/tests/Forms/Controls.DateTimeControl.value.phpt b/tests/Forms/Controls.DateTimeControl.value.phpt index ea4eb5981..557237069 100644 --- a/tests/Forms/Controls.DateTimeControl.value.phpt +++ b/tests/Forms/Controls.DateTimeControl.value.phpt @@ -24,6 +24,15 @@ test('invalid argument', function () { }); +test('empty string', function () { + $form = new Form; + $input = $form->addDate('date') + ->setValue(''); + + Assert::null($input->getValue()); +}); + + test('date as string', function () { $form = new Form; $input = $form->addDate('date')