- preg_match: documentation ( source)
- checkdate: documentation ( source)
<?php declare(strict_types=1);
class DateValidator
{
const DATE_FORMAT = 'd/m/Y'; // DD/MM/YYYY
const DATE_EXP = '/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/';
public static function validateHistoricalDate(string $dateString): HistoricalDate
{
$historicalDate = new HistoricalDate($dateString);
$date = DateTime::createFromFormat(self::DATE_FORMAT, $dateString);
if (!$date || !preg_match(self::DATE_EXP, $dateString, $dateParts)) {
$historicalDate->setMessage('Date is not in the required format DD/MM/YYYY [PHP - d/m/Y]');
return $historicalDate;
}
if (!checkdate((int) $dateParts[2], (int) $dateParts[1], (int) $dateParts[3])) {
$historicalDate->setMessage('Date is not valid');
return $historicalDate;
}
if ($date > new DateTime()) {
$historicalDate->setMessage('Date is not historical');
return $historicalDate;
}
$historicalDate->setValidity(true);
return $historicalDate;
}
}
class HistoricalDate
{
private $date;
private $valid = false;
private $message = '';
public function __construct(string $date)
{
$this->setDate($date);
}
public function setValidity(bool $value)
{
$this->valid = $value;
}
public function setMessage(string $message)
{
$this->message = $message;
}
public function isValid(): bool
{
return $this->valid;
}
public function getMessage(): string
{
return $this->message;
}
public function getDate(): string
{
return $this->date;
}
private function setDate(string $date)
{
$this->date = $date;
}
}
$dateString = "99/02/2017";
$result = DateValidator::validateHistoricalDate($dateString);
if (!$result->isValid()) {
$message = $result->getMessage();
}
echo $result->isValid() ? 'Valid date' : $message;