fullybaked | davebaker

I'm a developer living in the UK and when I'm not spending time with my wife and our 2 wonderful little boys, I love hacking around with code

I'm passionate about technology, web development, gaming and fencing

15 February 2013

Add 'on-the-fly' validations to CakePHP

Normally all the validation rules are stored in the model class in the validate var

public $validate = array();

However, sometimes you need to add a rule only in certain situations, maybe depending on something in the request. This is where dynamic validation comes in, with the help of the Hash class (in Cakephp <= 2.2 use Set class)

A typical validation rule in the model

// Model/Post.php

public $validate = array(
  'title' => array(
    'rule' => 'notEmpty',
    'message' => 'Title must be supplied'

Add additional rules from controller if required

// Controller/PostsController.php

if ($condition) {
  $this->Post->validate = Hash:merge(
      'content' => array(
        'rule' => 'notEmpty',
        'message' => 'You must add content'

This could be handy when some rules are only required in some cases.

If you want to keep you 'thin controller - fat model' architecture, these dynamic validations could be refactored into the model and called from the controller when required.