You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.0 KiB

13 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
13 years ago
namespace yii\validators;
use Yii;
use DateTime;
13 years ago
/**
* DateValidator verifies if the attribute represents a date, time or datetime in a proper format.
13 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
13 years ago
* @since 2.0
13 years ago
*/
13 years ago
class DateValidator extends Validator
13 years ago
{
/**
* @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.
13 years ago
*/
public $format = 'Y-m-d';
13 years ago
/**
* @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;
/**
* Initializes the validator.
*/
public function init()
{
parent::init();
if ($this->message === null) {
$this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
}
}
/**
13 years ago
* Validates the attribute of the object.
* If there is any error, the error message is added to the object.
13 years ago
* @param \yii\base\Model $object the object being validated
13 years ago
* @param string $attribute the attribute being validated
*/
13 years ago
public function validateAttribute($object, $attribute)
13 years ago
{
$value = $object->$attribute;
if (is_array($value)) {
$this->addError($object, $attribute, $this->message);
return;
}
$date = DateTime::createFromFormat($this->format, $value);
if ($date === false) {
$this->addError($object, $attribute, $this->message);
12 years ago
} elseif ($this->timestampAttribute !== null) {
$object->{$this->timestampAttribute} = $date->getTimestamp();
13 years ago
}
}
/**
* Validates the given value.
* @param mixed $value the value to be validated.
* @return boolean whether the value is valid.
*/
public function validateValue($value)
{
return DateTime::createFromFormat($this->format, $value) !== false;
}
13 years ago
}