4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class DateValidator extends ConstraintValidator
23 const PATTERN = '/^(\d{4})-(\d{2})-(\d{2})$/';
26 * Checks whether a date is valid.
28 * @param int $year The year
29 * @param int $month The month
30 * @param int $day The day
32 * @return bool Whether the date is valid
36 public static function checkDate($year, $month, $day)
38 return checkdate($month, $day, $year);
44 public function validate($value, Constraint $constraint)
46 if (!$constraint instanceof Date) {
47 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Date');
50 if (null === $value || '' === $value || $value instanceof \DateTimeInterface) {
54 if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
55 throw new UnexpectedTypeException($value, 'string');
58 $value = (string) $value;
60 if (!preg_match(static::PATTERN, $value, $matches)) {
61 $this->context->buildViolation($constraint->message)
62 ->setParameter('{{ value }}', $this->formatValue($value))
63 ->setCode(Date::INVALID_FORMAT_ERROR)
69 if (!self::checkDate($matches[1], $matches[2], $matches[3])) {
70 $this->context->buildViolation($constraint->message)
71 ->setParameter('{{ value }}', $this->formatValue($value))
72 ->setCode(Date::INVALID_DATE_ERROR)