avatar

CakePHP - trimming form post values for empty data validation

March 3rd, 2008 in 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))
  10. array_walk_recursive($this->data, array($this, 'whitespace'));
  11. }
  12. }
  13. ?>

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

Enjoy!

5 comments so far

  1. gravatar
    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
    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
    mattm September 24th, 2008 at 21:20:37
    just what i needed, thank you very much.
  4. gravatar
    Programming guru May 12th, 2009 at 01:35:24
    Thanks Gurde...
    Today, it's great help me.
    Thanks again.
  5. gravatar
    Snakes August 7th, 2009 at 03:23:35
    Great trick!

    I think it would be a good idea to rename whitespace() to __whitespace() so cake will consider it private.

    Also, be sure to call parent::beforeFilter(); in any of your derived classes that have their own beforeFilter(). If you don't - this won't get called!

Post your comment