How can I do a filter validation?

Hi folks,

I need to create some customized validations in some controller actions and I think that filters is the best way to do it.

I intend to create a filter class and use the method to validate data, but I don’t know how can I use filter how validate rules.

I’d like know if anyone have a exemple?

Thanks

why would you want to perform validation in a controller rather than a model?

Hi bettor,

I have 2 controllers and 4 actions on each one and I need use the same validation in all this actions.

I think that is very laborious to do this on each controller, and probably I’ll use this validation in more places.

The validation is very simple, I’ll receive a list of words and transform that in a regexp, so i need to compare the user post to know if on of this words was on the list, if true, no store post on database, else store the post.

Thanks,

You can have one million controllers and as much actions if you wish…Yii is so flexible that in every action you can define $model=new Modelname; Than when you call $model->save() Yii will validate all your input for you. In your Modelname model you should define your validation rules. The way you are describing your application you should use [probably] ‘in’, ‘range’=>‘1,2,3’…etc [I am just guesssing here as I cannot see your code]. If I am not misunderstanding anything I do not see a reason for you to use validation in your controller rather than in your model. If you need more specific help please quote some code so I can provide more precise examples.

regards,

b

bettor,

I know that I can use the model validations (actually I’ll do this), but I don’t like the idea to repeat the same method in all models that I need, each controller will be work with a different model, so I need to create a method global and call it how a validation.

Do you have any exemple of CFilterValidator in rules method?

Thanks.

Perhaps you should have a ‘base’ Model class with the


<?php

class MyBaseActiveRecord extends CActiveRecord {

	public function rules() {

		return array(

			array('pop_id, name, create_date, status_id', 'required'),

			array('blah_id', 'numerical', 'integerOnly'=>true),

			array('pop_id, name, uom_id, curr_id', 'safe'),

			array('name', 'safe', 'on'=>'search'),

		);

	}

} 

?>

And then extend this class further?


<?php

class Post extends MyBaseActiveRecord {

	public function rules() {

		$rules = parent::rules();

		$rules[] = array(

			array('pop_id, name, create_date, status_id', 'required'),

			array('blah_id', 'numerical', 'integerOnly'=>true),

			array('pop_id, name, uom_id, curr_id', 'safe'),

			array('name', 'safe', 'on'=>'search'),

		);

		return $rules;

	}

} 

?>

… just thinking out 'loud…