how to reuse the rules defined in rules in ajax validation?

sorry for my bad english …

the title wrong

i want to say "how to reuse the model rules in ajax validation?"

for example,

//rules defined in model Post

public function rules()

{

return array(

array(‘title, content, status’, ‘required’),

array(‘status’, ‘in’, ‘range’=>array(1,2,3)),

array(‘title’, ‘length’, ‘max’=>128),

array(‘tags’, ‘match’, ‘pattern’=>’/^[\w\s,]+$/’, ‘message’=>‘Tags can only contain word characters.’),

array(‘tags’, ‘normalizeTags’),

array(‘title, status’, ‘safe’, ‘on’=>‘search’),

);

}


class ajaxController extends Controller{

public function actionValidateTags(){

//how to reuse the rules in Post::rules????????

}

}


Validation is performed in models, not in controllers.

Any controller can validate data for a certain model by creating an instance of the model in its action.

So, why don’t you create a model instance in your controller.

BTW, ‘ajaxController’ seems something very strange to me.

Yii will take care of the ajax validation without much extra coding.

From the api:

check http://www.yiiframework.com/doc/api/1.1/CActiveForm

thanks for reply

2 things i’am confusing

1:when the user finish username,he ‘tab’ to password,then i want to ajax validate username.

what is the best way to organize my code

2.eg. for page like post show ,there is only one input :comment content.

should i create a class :CommentForm extends CFormModel.

i think this way is not perfect.

Use CActiveForm, and it will do all those things for you.

In fact, yiic-generated skeleton Yii app already has the kind of login form that you are trying to write for yourself.

The number of the fields will not be a problem.

And where do you plan to save those comments?

I think you need some database table to save them, as you see in the blog tutorial of Yii.

If you are going to use a database table, then you should use an active record model for it. And it will make things much simpler and easier.

thans,you resolve my confuse.

but,i look at the CActiveForm ,

when registering,if i want only to ajax validate password,it will be also to validate username,eg.username required,username not exists.(i saw yii source code in CActiveForm::validate)

the extra validate i don’t want !




$model->validate($attributes);

foreach($model->getErrors() as $attribute=>$errors)

	$result[CHtml::activeId($model,$attribute)]=$errors;



it wiil validate all attributes .not password only

how to deal with this problem?

Define scenario based validation rules in the model.

Creating model