Use The Validator Of A Model In A Form Model

The API writes ( that you can use a model class method as a validation rule. Is it possible to use the rules() of a model as a validation rule for an CFormModel instance?

I have a CActiveRecord in which I have a unique field and I want to use that unique validator in the form model. Is this simply possible by adding a rule to the rules() in the CFormModel instance or should I define a method in the specific CFormModel or CActiveRecord and add that as a validator?

I’ve tried searching without success. Anyone ever tried this or know pointers to documentation?

Hi Arno,

You can simply add ‘unique’ rule to the rules method of your CFormModel. But you have to specify ‘className’ property explicitly when you want to use CUniqueValidator in a CFormModel (or in other CAcitveRecord).

Briljant! thank you.

In my case I also needed the ‘attributeName’ to get the attribute correct.

public function rules()


    return array(


        array('Company', 'unique', 'className'=>'Relation', 'attributeName'=>'Name' ),




Yeah, I forgot to mention that, but you got it.

Yii’s validators for models are sweat, aren’t they?

It took me some to comprehend all possibilities but now that I know my way around a bit; awesome!!

I only find the documentation a bit on the weak side, you need to be aware of the ‘greater picture’ to understand things and see possibilities to let Yii do the work for you, but once you do… How did I ever do without? B)