Yii2 Bootstrap 3
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.

74 lines
1.8 KiB

14 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
14 years ago
* @license http://www.yiiframework.com/license/
*/
14 years ago
namespace yii\validators;
use Yii;
use DateTime;
14 years ago
/**
* DateValidator verifies if the attribute represents a date, time or datetime in a proper format.
14 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
13 years ago
* @since 2.0
14 years ago
*/
13 years ago
class DateValidator extends Validator
14 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.
14 years ago
*/
public $format = 'Y-m-d';
14 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;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->message === null) {
$this->message = Yii::t('yii', 'The format of {attribute} is invalid.');
}
}
/**
* @inheritdoc
14 years ago
*/
14 years ago
public function validateAttribute($object, $attribute)
14 years ago
{
$value = $object->$attribute;
$result = $this->validateValue($value);
if (!empty($result)) {
$this->addError($object, $attribute, $result[0], $result[1]);
12 years ago
} elseif ($this->timestampAttribute !== null) {
$date = DateTime::createFromFormat($this->format, $value);
$object->{$this->timestampAttribute} = $date->getTimestamp();
14 years ago
}
}
/**
* @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;
}
14 years ago
}