Yii - How To Write Validation Rules For A Cformmodel

I’m new to Yii framework. I 'm using Yii framework for my application. Now , the data is extracted from XML file and not from database.The data entered into textfield is also converted to XML file. The model class extends CFormModel . I have a textfield that should allow only integers. I did a front end validation using Javascript that works fine for some browsers but not most. So, I want to do a backend validation using rules(). How can I write the validation rule for this to allow integers.

Add this rule to model

public function rules()


{


	return array(


		


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


	);


}

does not work rahul

I think you may need to turn on ajax or client validation.

View:




<?php $form=$this->beginWidget('CActiveForm', array(

	'enableAjaxValidation'=>true,

)); ?>



Controller:




	public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		$this->performAjaxValidation($model);


		if(isset($_POST['MyModel']))

		{

			$model->attributes=$_POST['MyModel'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}



Add also to actionCreate

or for client side:

View:




<?php $form=$this->beginWidget('CActiveForm', array(

	'enableClientValidation'=>true,

)); ?>



to use validations of a model, I think you need ACTIVE form/model insteal of formModel.

please see this forum

I hope it’s some help

You can do validations even without an actuall model. You’ll need to make dummy for validations. As example:




class MyValidator extends CFormModel {

    public function __get($name) {

        return isset($_POST[$name])?$_POST[$name]:null;

    }

    static function myValidate( Array $rules ) {

        $dummy = new MyValidator();

        foreach($rules as $rule) {

            if( isset($rule[0],$rule[1]) ) {

                $validator = CValidator::createValidator( 

                     $rule[1], 

                     $dummy, 

                     $rule[0], 

                     array_slice($rule,2) 

                );

                $validator->validate($dummy);

            }

            else { /* throw error; */ }

        }


        //print_r( $dummy->getErrors() );

        return !$dummy->hasErrors();

    }

}

//use of this

$rules = array(

    array('name, email', 'required'),

    array('email', 'email'),

);


if( MyValidator::myValidate($rules) ) {

    ....

}



For this, just put your attributes to validate in $_POST.