Add 'on-the-fly' validations to CakePHP

 Feb 15, 2013

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

<?php
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

<?php
// Model/Post.php

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

Add additional rules from controller if required

<?php
// Controller/PostsController.php

if ($condition) {
  $this->Post->validate = Hash:merge(
    $this->Post->validate,
    array(
      '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.