How to validate a date
Short answer
Parse the string by a format and make sure the same string comes back:
<?php
function isValidDate(string $value, string $format = 'd.m.Y'): bool
{
$date = DateTimeImmutable::createFromFormat($format, $value);
return $date !== false && $date->format($format) === $value;
}
var_dump(isValidDate('30.01.2025'));
var_dump(isValidDate('31.02.2025'));
var_dump(isValidDate('tomorrow'));Output:
bool(true)
bool(false)
bool(false)Why compare the result
PHP "fixes" non-existent dates by itself: 31 February becomes early March, with no error:
<?php
echo DateTimeImmutable::createFromFormat('d.m.Y', '31.02.2025')->format('d.m.Y');Output:
03.03.2025Separate numbers
If the day, month and year arrive separately, checkdate() is enough:
<?php
var_dump(checkdate(2, 31, 2025));Output:
bool(false)Functions used in this recipe
- checkdate — Checks whether such a date exists.
- DateTimeImmutable — A date and time object that cannot be changed: every operation returns a new object.
- strtotime — Turns a textual date description into a timestamp.