DateValidator.php 2.04 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
8 9
namespace yii\validators;

Qiang Xue committed
10 11 12
use Yii;
use DateTime;

w  
Qiang Xue committed
13
/**
Qiang Xue committed
14
 * DateValidator verifies if the attribute represents a date, time or datetime in a proper format.
w  
Qiang Xue committed
15 16
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Alexander Makarov committed
17
 * @since 2.0
w  
Qiang Xue committed
18
 */
Alexander Makarov committed
19
class DateValidator extends Validator
w  
Qiang Xue committed
20
{
21 22 23 24 25 26 27 28 29 30 31 32
    /**
     * @var string the date format that the value being validated should follow.
     * Please refer to <http://www.php.net/manual/en/datetime.createfromformat.php> on
     * supported formats.
     */
    public $format = 'Y-m-d';
    /**
     * @var string the name of the attribute to receive the parsing result.
     * When this property is not null and the validation is successful, the named attribute will
     * receive the parsing result.
     */
    public $timestampAttribute;
w  
Qiang Xue committed
33

34 35 36 37 38 39 40 41 42 43
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if ($this->message === null) {
            $this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
        }
    }
Qiang Xue committed
44

45 46 47 48 49 50 51 52 53 54 55 56 57 58
    /**
     * @inheritdoc
     */
    public function validateAttribute($object, $attribute)
    {
        $value = $object->$attribute;
        $result = $this->validateValue($value);
        if (!empty($result)) {
            $this->addError($object, $attribute, $result[0], $result[1]);
        } elseif ($this->timestampAttribute !== null) {
            $date = DateTime::createFromFormat($this->format, $value);
            $object->{$this->timestampAttribute} = $date->getTimestamp();
        }
    }
Qiang Xue committed
59

60 61 62 63 64 65 66 67 68 69 70 71 72 73
    /**
     * @inheritdoc
     */
    protected function validateValue($value)
    {
        if (is_array($value)) {
            return [$this->message, []];
        }
        $date = DateTime::createFromFormat($this->format, $value);
        $errors = DateTime::getLastErrors();
        $invalid = $date === false || $errors['error_count'] || $errors['warning_count'];

        return $invalid ? [$this->message, []] : null;
    }
w  
Qiang Xue committed
74
}