Validation in CakePHP 1.3

How to go about doing validation when using CakePHP 1.3

This is such a crucial task to many apps and is something that CakePHP has made very simple - unfortunately it hasn't been documented anywhere easily accessible on the Cake site - The book splits up validation across several chapters and many of the tutorials online focus on older versions of Cake or are simply wrong.

Naturally then what we need is another blog post on the subject! This will explain how I perform validation in CakePHP 1.3. I am not saying this is the best way, or the only way, but it is a way that works for me.


Because validation is essentially giving your data some meta-data to say 'This data needs to have x, y or z before I allow it to be saved' it makes sense that we need to go into the model to get everything kicked off.

I won't go into too much detail on the options available as these are covered in the book, but basically you need to put in a variable called $validate;


var $validate = array(
'name' => array(
'rule'       => 'alphaNumeric',
'required'   => true,
'allowEmpty' => false,
'message'    => 'Please enter your name'
'email' => array(
'rule'       => 'email',
'required'   => true,
'allowEmpty' => false,
'message'    => 'Please enter your email address'


Obviously replace the fields and rules with your own, but that is the basic idea.


In the controller I perform a test to see if the data is valid before saving, if it is then you save as normal, if it isn't then I append the error messages into the inbuilt flash function.



if ($this->Contact->validates()) {
//Normal Saving Stuff
} else {
$this->Session->setFlash(__(implode('<br />', $this->Contact->invalidFields()), true));

The three important things here are;

  • Setting the data to the model
  • Doing the validates() check
  • Imploding the error array to make it a string for the setFlash function

Hopefully this helps someone stuck with CakePHP validation.

Recent posts View all


How to ignore Bullet in RSpec tests

Using Bullet during a test can pick up mistakes but also has false negatives; here is an easy way to ignore them


How we used Nokogiri to fix a sizing issue in YouTube's oEmbed

At some point, one of our calls to YouTube's oEmbed endpoint was returning videos way too small; we fixed in in our Rails application by using Nokogiri