diff options
Diffstat (limited to 'protected/components/DateCompareValidator.php')
| -rw-r--r-- | protected/components/DateCompareValidator.php | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/protected/components/DateCompareValidator.php b/protected/components/DateCompareValidator.php new file mode 100644 index 0000000..c013382 --- /dev/null +++ b/protected/components/DateCompareValidator.php @@ -0,0 +1,57 @@ +<?php +class DateCompareValidator extends CValidator { + /** + * @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; + public $operator = '>'; + public $compareAttribute; + public $compareValue; + + /** + * Validates the attribute of the object. + * If there is any error, the error message is added to the object. + * @param CModel $object the object being validated + * @param string $attribute the attribute being validated + */ + protected function validateAttribute($object, $attribute) { + if ((empty($this->compareAttribute) && empty($this->compareValue)) || empty($this->operator)) { + $this->addError($attribute, 'Invalid Parameters to dateCompare'); + } + + $compareAttribute = $this->compareAttribute; + $this->compareValue = empty($compareAttribute) ? $this->compareValue : $object->$compareAttribute;; + + if ($this->allowEmpty && empty($this->compareValue)) { + return; + } + + $start = CDateTimeParser::parse($object->$attribute, $this->format); + + $end = CDateTimeParser::parse($this->compareValue, $this->format); + + //a little php trick - safe than eval and easier than a big switch statement + + if (version_compare($start, $end, $this->operator)) { + return; + } else { + $message = $this->message !== null ? $this->message : Yii::t('astaf', 'The value of {attribute} ({value}) is not {operator} {compareAttribute} ({compareValue}).'); + $this->addError($object, $attribute, $message, array('{operator}'=>$this->operator, '{compareValue}'=>$this->compareValue, '{value}'=>$object->$attribute, '{compareAttribute}'=>($object->getAttributeLabel($this->compareAttribute)))); + } + + } +}
\ No newline at end of file |
