comparison date

I wanted to ask if anyone knows if there are validators or functions of the framework with checks that a date entered is greater or less than the previous or next …

Or do I insert a javascript for comparing two dates?

I don’t know if Yii has this, but I think it is best to do with Javascript since it works in the client side and this task shouldn’t do with PHP. It is also a performance issue I guess.

I always hate to trust the front end as my only line of defense. You could use something like this:





class DateCompareValidator extends CValidator

{


	public $allowEmpty=true;

	public $compareType='greaterThan';

	public $compareDate=date('Y-m-d');

	


    protected function validateAttribute($model,$attribute) {


		if(empty($model->$attribute) $$ $this->allowEmpty) {

			return;

		}

		

		$modelTimestamp = strtotime($model->$attribute);

		$compareTimestamp = strtotime($this->compareDate);

		

		if($modelTimestamp === false) {

        	$errorMessage = "This value does not appear to be a validate date.";

	        $model->addError($attribute,$errorMessage);

	        return false;

		}

		

		if($compareTimestamp === false) {

        	throw new Exception('Invalid comparison date sent to DateCompareValidator.');

		}

		

		if($this->compareType === 'greaterThan') {

			if($modelTimestamp > $compareTimestamp) {

				return true;

			}

        	$errorMessage = "This value must be greater than {$this->compareDate}.";

	        $model->addError($attribute,$errorMessage);

	        return false;

		} else if($this->compareType === 'lessThan') {

			if($modelTimestamp < $compareTimestamp) {

				return true;

			}

        	$errorMessage = "This value must be less than {$this->compareDate}.";

	        $model->addError($attribute,$errorMessage);

	        return false;

	    } else {

	    	throw new Exception("Unsupported date comparison type sent to DateCompareValidator.");

	    }

	

    }

}




and then use it like this in your model:





	public function rules()

	{

		return array(

			array('myDateField', 'dateCompare', 'compareDate'=>'05-01-2010', 'allowEmpty' => true, 'compareType' => 'greaterThan'),

		);

	}



just make sure to import the validator in your main config file. Also note that I have not tested this code out, I just wrote it in the forum message board. Please be aware that there may be typos, and the actual code may need more checks. I hope this helps! Let me know.

Corey

Thank you! It finally makes sense.