Changing when Yii builds model rules

Hi everyone.

I have noticed recently when trying to use a certain type of rule that Yii builds the validation rules for a model as soon as it is loaded instead of on validate().

This is causing a problem for me. I am using a rule which relies upon another variable of the model:

array('version', 'in', 'range' => $this->versions($this->title_type, true)),

The problem is that this rule gets initialised before the variable $title_type is ready (or rather initialised) to decide the content of the range for the value of version since $title_type also comes from the form into the validation methods.

I was wondering whether or not there is a way to tell Yii to kinda refresh the validation rules on validate, maybe in the function signature or something (unfortunately all I see is everything but that)?


Just add the validator programmatically:

public function beforeValidate() {

  $validator = new CRangeValidator;

  $validator->range = $this->versions($this->title_type, true);


  return parent::beforeValidate();


Sweet cheers that worked.

I knew there was a way of manually adding validation rules but it is not that well documented.

Thanks again :)

This doesn’t work properly, as the attributes for this validator will have to be added as well. Use the following for this to work. Instead of using “$validator = new Validator;” (which didn’t add the validator properly to the list of validators for a given scenario) use CValidator’s static “createValidator” method:


            'CRangeValidator', $this, // type of validator and model

            'version', // attribute or list of attributes

            array( // params

                'range'=>$this->versions($this->title_type, true),



See for details.