PHP / mySQL Jump to comments
In CakePHP it is possible to make rules to validate form post values. In the model you use $validate as an array of validation rules.

Usually this would look like this:
  1. var $validate=Array("input_name"=>VALID_NOT_EMPTY);

This is all good unless somebody is inserting spaces. At that point the validation returns true and saves spaces into your database table. I guess that is not the desired result. One solution would be to trim individually every input in the controller before validation. That would result in too many lines. CakePHP should have this built in.

The other solution for doing this and loosing those extra lines it is to put the following code in your app_controller.php:
  1. <?php
  2. class AppController extends Controller {
  3. function whitespace(&$value,&$key){
  4. $key=trim($key);
  5. $value=trim($value);
  6. }
  7.  
  8. function beforeFilter(){
  9. if(!empty($this->data)) array_walk_recursive($this->data,Array($this,'whitespace'));
  10. }
  11. }
  12. ?>

Doing this the values are trimmed and the validation rule returns false for inputs containing only spaces.

Enjoy!

3 comments so far

  1. gravatar
    # 1
    eric
    July 19th, 2008 at 03:42:12

    Thanks! That's just what I was looking for.

    Quick question: When I upgrade cakePHP, will I lose those changes?

  2. gravatar
    # 2
    gurde
    July 21st, 2008 at 07:06:47

    @eric: When you upgrade CakePHP you just update the cake directory. The app directory remains untouched. You have to put the above code in /app/app_controller.php so you won't need to ajust /cake/app_controller.php every time you update CakePHP.

  3. gravatar
    # 3
    mattm
    September 24th, 2008 at 21:20:37

    just what i needed, thank you very much.

Post your comment