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.

77 lines
2.0 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;
/**
* Initializes the validator.
*/
public function init()
{
parent::init();
if ($this->message === null) {
$this->message = Yii::t('yii|The format of {attribute} is invalid.');
}
}
/**
14 years ago
* Validates the attribute of the object.
* If there is any error, the error message is added to the object.
14 years ago
* @param \yii\base\Model $object the object being validated
14 years ago
* @param string $attribute the attribute being validated
*/
14 years ago
public function validateAttribute($object, $attribute)
14 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);
} elseif ($this->timestampAttribute !== false) {
$object->{$this->timestampAttribute} = $date->getTimestamp();
14 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;
}
14 years ago
}