1: <?php
2: /**
3: * CDateValidator class file.
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CDateValidator verifies if the attribute represents a date, time or datetime.
13: *
14: * By setting the {@link format} property, one can specify what format the date value
15: * must be in. If the given date value doesn't follow the format, the attribute is considered as invalid.
16: *
17: * @author Qiang Xue <qiang.xue@gmail.com>
18: * @version $Id: CDateValidator.php 2799 2011-01-01 19:31:13Z qiang.xue $
19: * @package system.validators
20: * @since 1.1.7
21: */
22: class CDateValidator extends CValidator
23: {
24: /**
25: * @var mixed the format pattern that the date value should follow.
26: * This can be either a string or an array representing multiple formats.
27: * Defaults to 'MM/dd/yyyy'. Please see {@link CDateTimeParser} for details
28: * about how to specify a date format.
29: */
30: public $format='MM/dd/yyyy';
31: /**
32: * @var boolean whether the attribute value can be null or empty. Defaults to true,
33: * meaning that if the attribute is empty, it is considered valid.
34: */
35: public $allowEmpty=true;
36: /**
37: * @var string the name of the attribute to receive the parsing result.
38: * When this property is not null and the validation is successful, the named attribute will
39: * receive the parsing result.
40: */
41: public $timestampAttribute;
42:
43: /**
44: * Validates the attribute of the object.
45: * If there is any error, the error message is added to the object.
46: * @param CModel $object the object being validated
47: * @param string $attribute the attribute being validated
48: */
49: protected function validateAttribute($object,$attribute)
50: {
51: $value=$object->$attribute;
52: if($this->allowEmpty && $this->isEmpty($value))
53: return;
54:
55: $valid=false;
56:
57: // reason of array checking is explained here: https://github.com/yiisoft/yii/issues/1955
58: if(!is_array($value))
59: {
60: $formats=is_string($this->format) ? array($this->format) : $this->format;
61: foreach($formats as $format)
62: {
63: $timestamp=CDateTimeParser::parse($value,$format,array('month'=>1,'day'=>1,'hour'=>0,'minute'=>0,'second'=>0));
64: if($timestamp!==false)
65: {
66: $valid=true;
67: if($this->timestampAttribute!==null)
68: $object->{$this->timestampAttribute}=$timestamp;
69: break;
70: }
71: }
72: }
73:
74: if(!$valid)
75: {
76: $message=$this->message!==null?$this->message : Yii::t('yii','The format of {attribute} is invalid.');
77: $this->addError($object,$attribute,$message);
78: }
79: }
80: }
81:
82: