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.

Model

Because validation is 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 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'
)
);

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

Controller

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.

$this->Contact->set($this->data);

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

VS CodeWeb Dev

Select multiple lines in VS Code

How to select multiple lines to edit at once within VS Code

VS Code Web Dev

Move a line up or down with VS Code

A quick tip on moving lines up or down a file using your keyboard in VS Code