Skip to content

Commit

Permalink
Implement type=datetime-local
Browse files Browse the repository at this point in the history
  • Loading branch information
g105b committed Dec 31, 2019
1 parent 3dbfdfa commit 8d3943a
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Rule/TypeDate.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ class TypeDate extends Rule {
const FORMAT_DATE = "Y-m-d";
const FORMAT_MONTH = "Y-m";
const FORMAT_WEEK = "Y-\WW";
const FORMAT_DATETIME_LOCAL = "Y-m-d\TH:i";

protected $attributes = [
"type=date",
"type=month",
"type=week",
"type=datetime-local",
];

public function isValid(DOMElement $element, string $value):bool {
Expand All @@ -40,7 +42,7 @@ public function isValid(DOMElement $element, string $value):bool {

case "week":
if(strstr($value, "-W")) {
list($year, $week) = explode("-", $value);
[$year, $week] = explode("-", $value);
}
else {
return false;
Expand All @@ -57,6 +59,13 @@ public function isValid(DOMElement $element, string $value):bool {
}

break;

case "datetime-local":
$dateTime = DateTime::createFromFormat(
self::FORMAT_DATETIME_LOCAL,
$value
);
break;
}

return $dateTime !== false;
Expand All @@ -78,6 +87,10 @@ public function getHint(DOMElement $element, string $value):string {
case "week":
$format = self::FORMAT_WEEK;
break;

case "datetime-local":
$format = self::FORMAT_DATETIME_LOCAL;
break;
}

return "Field must be a $type in the format $format";
Expand Down
36 changes: 36 additions & 0 deletions test/phpunit/Rule/TypeDateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,40 @@ public function testTypeWeekInvalid() {
);
}
}

public function testTypeDatetimeLocal() {
$form = self::getFormFromHtml(Helper::HTML_DATE_TIME);
$validator = new Validator();

$exception = null;

try {
$validator->validate($form, [
"datetime" => "2020-01-13T15:37",
]);
}
catch(ValidationException $exception) {}

self::assertNull($exception);
}

public function testTypeDatetimeLocalInvalid() {
$form = self::getFormFromHtml(Helper::HTML_DATE_TIME);
$validator = new Validator();

try {
$validator->validate($form, [
"datetime" => "2020-01-13 15:37:00", // not using the correct ISO-8601 format
]);
}
catch(ValidationException $exception) {
$errorArray = iterator_to_array($validator->getLastErrorList());
self::assertCount(1, $errorArray);
$monthErrorArray = $errorArray["datetime"];
self::assertContains(
"Field must be a datetime-local in the format Y-m-d\TH:i",
$monthErrorArray
);
}
}
}

0 comments on commit 8d3943a

Please sign in to comment.