How can i validate a non model attribute?

I have added a public property to my active record model class that doesn’t map to a real table column but i have that property/attribute in a form and i want to validate it with the current model. I have tried to add a validation rule to that public property but nothing happens on it. How can i achieve this?

When you add a public attribute to an AR, (at least in Yii 1.0) you must have to set the attribute in the controller like this:

if(isset($_POST[‘yourModel’]) {

$model->attributes = $_POST[‘yourModel’];

$model->newAttribute = $_POST[‘yourModel’][‘newAttribute’];

}

May be this was your problem, without this you never set the attribute value.

How about showing the snippets of what you tried.

add it to your rule as safe to be able to set it via $model->attributes =$_POST[‘yourModel’];




public $newAttribute=int; // or whatever type


public function rules() 

{

...

array('newAttribute','safe'),

}



this must work, afterwards you should also be able to set a specific rule for your type to have validation.

you can also add something like this for customized validation of your attribute




protected function beforeValidate()

{

          

                if(!($this->newAttribute))

                {

                    $error=Yii::t('yourmodel','You must fill newAttribute');

                    $this->addError('newAttribute',$error);

                }

           

        return parent::beforeValidate();

}



Yes, please do because what you describe should be working. Have a look at the LoginForm generated by yiic webapp, which does the same and works fine.

I have the same problem here :confused:

Well, your problem is also not going to be resolved without showing us any code.