Stripping Forms

Hey guys I have the following textfield in a form

 <div class>

        <?php echo $form->labelEx($model, 'Firstname'); ?>

        <?php echo $form->textField($model, 'Firstname', array('size' => 45, 'maxlength' => 45, 'ROWS' => 4)); ?>

        <?php echo $form->error($model, 'Firstname'); ?>


Which is recieved in the Controller class like follows,

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

Thats then saved to a database. What I want to know is if the user enters something like " /me" for their name how do I get it into "me". I basically want to get rid of any leading whitespaces and any unwanted characters like / - , ; etc. I have tried adding the following into the Model class but It did not work.

array('Firstname','filter','filter'=>array($obj=new CHtmlPurifier(),'purify')),

Nothing changes in the String at all.

EDIT: The first "/me" actually has a large amount of spaces in front of it, the forum automatically took it out…I wonder how it does that lol.

I’d not change the string the user inputed, I’d better add a validator, requiring the user to write correctly the name.

Maybe the user write ";eonard" just because teh L and the: are close, you should not take such decision for the user.

Use CRegularExpression like here.

Ah, Thank you very much, was exactly the kind of solution I was looking for. Thanks again :)

Hey, that works great for certain parts of the project but would you know a way in which only leading and trailing empty spaces are stripped from the form. Eg if someone types " Hello there " is there a way to either throw up and error about the spaces or could you change that to "Hello there". So basically get rid of the spaces at the start and the end but keep any spaces between words.

use trim() function of php. to get "Hello there" not " Hello there "

Hey that does seem like a useful function and normally this would pose no problems to implement but how do I implement it in yii. In the rules section or in the controller? Thanks for your help.

you can use it like this, write in model class

protected function beforeValidate() {

    	$this->Firstname = trim($this->Firstname);

    	return parent::beforeValidate();


Excellent, that works like a charm, Thank you very much.

As this is something that you could utilise in other models/forms, my advise would be to create your own filter and use that as a callback to a filter ‘rule’ in the model. Otherwise, you may find yourself repeating code.