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\Context\ExecutionContextInterface;
15 use Symfony\Component\Validator\Constraint;
16 use Symfony\Component\Validator\ConstraintValidator;
17 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
20 * @author Bernhard Schussek <bschussek@gmail.com>
22 class DateValidator extends ConstraintValidator
24 const PATTERN = '/^(\d{4})-(\d{2})-(\d{2})$/';
27 * Checks whether a date is valid.
29 * @param int $year The year
30 * @param int $month The month
31 * @param int $day The day
33 * @return bool Whether the date is valid
37 public static function checkDate($year, $month, $day)
39 return checkdate($month, $day, $year);
45 public function validate($value, Constraint $constraint)
47 if (!$constraint instanceof Date) {
48 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Date');
51 if (null === $value || '' === $value || $value instanceof \DateTime) {
55 if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
56 throw new UnexpectedTypeException($value, 'string');
59 $value = (string) $value;
61 if (!preg_match(static::PATTERN, $value, $matches)) {
62 if ($this->context instanceof ExecutionContextInterface) {
63 $this->context->buildViolation($constraint->message)
64 ->setParameter('{{ value }}', $this->formatValue($value))
65 ->setCode(Date::INVALID_FORMAT_ERROR)
68 $this->buildViolation($constraint->message)
69 ->setParameter('{{ value }}', $this->formatValue($value))
70 ->setCode(Date::INVALID_FORMAT_ERROR)
77 if (!self::checkDate($matches[1], $matches[2], $matches[3])) {
78 if ($this->context instanceof ExecutionContextInterface) {
79 $this->context->buildViolation($constraint->message)
80 ->setParameter('{{ value }}', $this->formatValue($value))
81 ->setCode(Date::INVALID_DATE_ERROR)
84 $this->buildViolation($constraint->message)
85 ->setParameter('{{ value }}', $this->formatValue($value))
86 ->setCode(Date::INVALID_DATE_ERROR)