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.

75 lines
2.3 KiB

14 years ago
<?php
/**
13 years ago
* DateValidator class file.
14 years ago
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
14 years ago
* @license http://www.yiiframework.com/license/
*/
14 years ago
namespace yii\validators;
14 years ago
/**
13 years ago
* DateValidator verifies if the attribute represents a date, time or datetime.
14 years ago
*
* By setting the {@link format} property, one can specify what format the date value
* must be in. If the given date value doesn't follow the format, the attribute is considered as invalid.
*
* @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 mixed the format pattern that the date value should follow.
* This can be either a string or an array representing multiple formats.
* Defaults to 'MM/dd/yyyy'. Please see {@link CDateTimeParser} for details
* about how to specify a date format.
*/
public $format = 'MM/dd/yyyy';
/**
* @var boolean whether the attribute value can be null or empty. Defaults to true,
* meaning that if the attribute is empty, it is considered valid.
*/
public $allowEmpty = true;
/**
* @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;
/**
* 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;
13 years ago
if ($this->allowEmpty && $this->isEmpty($value)) {
14 years ago
return;
13 years ago
}
14 years ago
$formats = is_string($this->format) ? array($this->format) : $this->format;
$valid = false;
13 years ago
foreach ($formats as $format) {
14 years ago
$timestamp = CDateTimeParser::parse($value, $format, array('month' => 1, 'day' => 1, 'hour' => 0, 'minute' => 0, 'second' => 0));
13 years ago
if ($timestamp !== false) {
14 years ago
$valid = true;
13 years ago
if ($this->timestampAttribute !== null) {
14 years ago
$object-> {$this->timestampAttribute} = $timestamp;
13 years ago
}
14 years ago
break;
}
}
13 years ago
if (!$valid) {
$message = ($this->message !== null) ? $this->message : \Yii::t('yii:The format of {attribute} is invalid.');
14 years ago
$this->addError($object, $attribute, $message);
}
}
}