CActiveRecordBehavior should add dynamically rules

is it somehow possible to add additional rules to a model via behavior?

if my behavior is added to a model, I’ve to ensure a certain value format (a date in my case).

Thanks for your help

Behaviors can’t add rules to models directly (AFAIK), but you can implement beforeValidate() or afterValidate() method in your behavior, and use addError() if an attribute is invalid.

try this

in your model (or base model)

public function rules()


    	$rules = array( /* your rules */ );

    	//add all rules from attached behaviors

        $behaviors = $this->behaviors();

        foreach($behaviors as $key=>$behavior)


            if( method_exists($this->{$key},'rules') )

                $rules += $this->{$key}->rules();


        return $rules;


and if you have extned models then

	public function rules()


		return array_merge(parent::rules(),array(

			/* your rules for this extended model */



(caution) Properties should not be conflicted.

You can process like that:

In your Behavior overwrite the attach method:


* Attach the behavior to the model.

* @param model $owner 


public function attach($owner) {



        $owner = $this->getOwner();

        $validators = $owner->getValidatorList();

        $params = array('types' => 'jpg, jpeg, gif, png'); // etc

        $validator = CValidator::createValidator('file', $owner, 'MyModel[attribute]',$params );