CFilterValidator

I am wracking my brain trying to figure out how the filter validator works.



	public function rules() {


		return array(


			array('username', 'length', 'min' => 2, 'max' => 255),


			array('password', 'length', 'min' => 8, 'max' => 255),


			array('email',    'length', 'min' => 6, 'max' => 255),


			array('handle',   'length', 'min' => 2, 'max' => 255),


			array('username, password, email', 'required'), // required fields


			array('username, email, handle', 'unique'), // unique values only


			array('email',    'email'), // is it an email address?


			array('created, modified', 'default', 'value' => new CDbExp​ression('NOW()')), // current timestamp


			array('username', 'filter' => trim($this->username)),


		);


	}


How is the filter suppose to work?  I learn by examples and I just can't seem to find any example usage of filter.

The Documentation states a few things but I don’t know how to format my rule to it to do something useful (like trim and strtolower).

Use 'trim' instead of trim($this->username).

It must be a valid PHP callback.

using:



array('username', 'filter', 'trim'),


I receive an error:

Quote

Property "CFilterValidator.0" is not defined.

Oh wait, my mistake!  using:



array('username', 'filter' => 'trim'),


I get:

Quote

User has an invalid validation rule. The rule must specify attributes to be validated and the validator name.

Your previous usage is correct.

HMM, I must be doing something incorrectly then.  Using:



	public function rules() {


		return array(


			array('username', 'length', 'min' => 2, 'max' => 255),


			array('password', 'length', 'min' => 8, 'max' => 255),


			array('email',    'length', 'min' => 6, 'max' => 255),


			array('handle',   'length', 'min' => 2, 'max' => 255),


			array('username, password, email', 'required'), // required fields


			array('username, email, handle', 'unique'), // unique values only


			array('email',    'email'), // is it an email address?


			array('created, modified', 'default', 'value' => new CDbExp​ression('NOW()')), // current timestamp


			array('username', 'filter', 'trim'),


		);


	}


I get a large error.  This is the description:

Quote

CException

Description

Property "CFilterValidator.0" is not defined.

Source File

/home/tlk/www/frameworks/yii/framework/validators/CValidator.php(138)

00126:            $validator->method=$name;

00127:            $validator->params=$params;

00128:        }

00129:        else

00130:        {

00131:            $params['attributes']=$attributes;

00132:            if(isset(self::$builtInValidators[$name]))

00133:                $className=Yii::import(self::$builtInValidators[$name],true);

00134:            else

00135:                $className=Yii::import($name,true);

00136:            $validator=new $className;

00137:            foreach($params as $name=>$value)

00138: $validator->$name=$value;

00139:        }

00140:

00141:        $validator->on=empty($on) ? array() : array_combine($on,$on);

00142:

00143:        return $validator;

00144:    }

00145:

00146:    /**

00147:      * Validates the specified object.

00148:      * @param CModel the data object being validated

00149:      * @param array the list of attributes to be validated. Defaults to null,

00150:      * meaning every attribute listed in {@link attributes} will be validated.

Stack Trace

#0 /home/tlk/www/frameworks/yii/framework/validators/CValidator.php(138): CComponent->__set('0', 'trim')

#1 /home/tlk/www/frameworks/yii/framework/base/CModel.php(380): CValidator::createValidator('filter', Object(User), 'username', Array)

#2 /home/tlk/www/frameworks/yii/framework/db/ar/CActiveRecord.php(1723): CModel->createValidators()

#3 /home/tlk/www/frameworks/yii/framework/db/ar/CActiveRecord.php(824): CActiveRecordMetaData->getValidators()

#4 /home/tlk/www/frameworks/yii/framework/base/CModel.php(259): CActiveRecord->getValidators()

#5 /home/tlk/www/frameworks/yii/framework/base/CModel.php(287): CModel->getValidatorsForAttribute('username', '')

#6 /home/tlk/www/frameworks/yii/framework/web/helpers/CHtml.php(862): CModel->isAttributeRequired('username', '')

#7 /home/tlk/www/gunpowdr.com/private/views/user/register.php(6): CHtml::activeLabelEx(Object(User), 'username')

#8 /home/tlk/www/frameworks/yii/framework/web/CBaseController.php(119): require('/home/tlk/www/g…')

#9 /home/tlk/www/frameworks/yii/framework/web/CBaseController.php(88): CBaseController->renderInternal('/home/tlk/www/g…', Array, true)

#10 /home/tlk/www/frameworks/yii/framework/web/CController.php(580): CBaseController->renderFile('/home/tlk/www/g…', Array, true)

#11 /home/tlk/www/frameworks/yii/framework/web/CController.php(510): CController->renderPartial('register', Array, true)

#12 /home/tlk/www/gunpowdr.com/private/controllers/UserController.php(170): CController->render('register', Array)

#13 /home/tlk/www/frameworks/yii/framework/web/actions/CInlineAction.php(32): UserController->actionRegister()

#14 /home/tlk/www/frameworks/yii/framework/web/CController.php(259): CInlineAction->run()

#15 /home/tlk/www/frameworks/yii/framework/web/filters/CFilterChain.php(128): CController->runAction(Object(CInlineAction))

#16 /home/tlk/www/frameworks/yii/framework/web/filters/CFilter.php(41): CFilterChain->run()

#17 /home/tlk/www/frameworks/yii/framework/web/CController.php(807): CFilter->filter(Object(CFilterChain))

#18 /home/tlk/www/frameworks/yii/framework/web/filters/CInlineFilter.php(59): CController->filterAccessControl(Object(CFilterChain))

#19 /home/tlk/www/frameworks/yii/framework/web/filters/CFilterChain.php(125): CInlineFilter->filter(Object(CFilterChain))

#20 /home/tlk/www/frameworks/yii/framework/web/CController.php(242): CFilterChain->run()

#21 /home/tlk/www/frameworks/yii/framework/web/CController.php(219): CController->runActionWithFilters(Object(CInlineAction), Array)

#22 /home/tlk/www/frameworks/yii/framework/web/CWebApplication.php(150): CController->run('register')

#23 /home/tlk/www/frameworks/yii/framework/web/CWebApplication.php(121): CWebApplication->runController('user', 'register')

#24 /home/tlk/www/frameworks/yii/framework/base/CApplication.php(170): CWebApplication->processRequest()

#25 /home/tlk/www/gunpowdr.com/public/index.php(11): CApplication->run()

#26 {main}

2009-02-20 15:21:01 Apache/2.2.9 (Ubuntu) PHP/5.2.6-2ubuntu4.1 with Suhosin-Patch Yii Framework/1.0.2

My knowledge of callbacks is a bit poor so I am reading up on them now.  I suppose all I really want to do is sanitize the username.  Make sure it's trim and alphanumeric and what not.

My bad. the rule should be array('username', 'filter', 'filter'=>'trim')

Perfect!  Thank you very much!  This is the very reason why I like Yii :)

It only works, when I use "trim" as filter, but when I want to use:

array('strPassword','filter','filter'=>'preparePassword')

I still get an error:

The "filter" property must be specified with a valid callback.

"public function preparePassword()" is in the same model containing this rule. Has it got to be somewhere else?

use 'filter'=>array($this,'preparePassword')

Just to share my experience with filter:

Given:

issue with Date defaulting to ‘0000-00-00’

Solution:

Incorporated the following code in the same model class in which the date field belongs




        public  function emptyToNull($value)

        {

               return ($value==='' || $value==='0000-00-00')? null : $value;

        }



The following has been my own code within the rules function




        array('birthdate', 'filter', 'filter'=>array($this,'emptyToNull')),

        ...



Hope this helps …