Posts tagged with “”

Learning CakePHP: Validation

I started developing for the web sometime in 1995 while I was still in the military. I “turned pro” in 1997. At that time there were two methods of data validation: client-side and server-side. Yeah, I know, that’s still all we have, but I think that Ajax has helped to blur the line between the two – perceptually, I mean, not technically.


Even back then I hated duplication. Frankly, I hated doing validation at all; I damn sure hated doing it twice. Moreover, I hated server-side validation because doing it (without also doing a whole lot of extra work) involved:

  1. Submitting a form to an action page
  2. Having that action page validate the form values
  3. Displaying (what was usually) an ugly error message to the user
  4. Asking the user to use their Back button to return to the form
  5. Expecting the user to remember the errors that had been displayed
  6. Asking the user correct each error
  7. Rinse
  8. Repeat

That’s a lot of lousy user experience. Since that sucked so mightily, I chose client-side. With Javascript, I could validate user input without having to make the round trip to the server. Talk to me all you want about graceful degradation, but first of all, that concept didn’t exist in 1996 and second…this is Javascript we’re talking about.


With the relatively recent proliferation of API‘s, server-side validation has taken on a whole new urgency. With multiple gateways into an application’s business core, it’s more critical than ever that validation be moved as far down the application stack as possible in order to eliminate redundancy and, in the process, ensure consistency. For most applications that I’ve built in the last 5 years or so, there’s been some kind of API involved.

With CakePHP

Once I had worked with CakePHP for a few months, I got comfortable enough to start thinking about validation and how I wanted it to work from end-to-end. I had a few requirements:

  1. I only wanted to write my rules and messages once. Do something once and you don’t have to worry about consistency. One less pain point is always going to be a good thing.
  2. I wanted to be able to validate without necessarily saving. Most of the time I’d be doing both, but decoupling them is just a good idea.
  3. Hide from the user the fact that my validation was happening on the server. To them, generating and displaying error messages should be a smooth and seamless experience.

I came up with something that seems reasonably elegant and has met my needs to date.

The Basics

Although I’m not a big fan of the semantics, CakePHP nicely decouples the validation and save actions. I would expect this of any framework, of course, but that’s a place to start. If I’m validating something independent of a save operation, I usually want that validation to return one or more error messages. CakePHP makes this easy and even offers me a convenient means of using my preferred semantics.

Never, Ever Mess With the Core

This is one of my basic tenets for developing with third-party libraries. Messing with core code is almost certain to destroy your upgrade path. Find another way.

In this case, I want to be able to validate model data based on the rules defined by that model and I want this validation to be available to all models in my application in exactly the same way. To do that, I created a copy of CakePHP’s app_model.php file as app/app_model.php. By creating a copy in my app/ directory, I can preserve my upgrade path, but still inherit from the proper parent class.


In the newly copied AppModel class, I added this function:

 * function validate
 * Validates model data. This function can be called independently
 * on any model for validation independent of a save operation. It
 * can also be overridden, for example, by a model requiring more
 * complex validation.
 * param   $data
 * return  array     An array of error messages or an empty array
 *                   if the data validates properly.
public function validate ( $data = array() ) { $this->set ( $data );

/** * Corrected based on input from Miles Johnson in the comments * below. */ return !$this->validates() ? $this->validationErrors : array(); }

That snippet alone provides basic validation across my entire application with a simple line of code:

Model->validate ( $this->data )

Complex validation

Something of a misnomer since this isn’t very complex, but there are times when more is required. For example, if I have customers and vendors that have addresses, I usually want to break the address out so that the data structure can be shared. Separate table, separate model. The data is abstracted, but I can’t really have a valid customer or vendor unless their address also validates. To do that, I need to override my simple validate() method in the Vendor (or Customer) model so that I can do just a little bit more:

public function validate ( $data = array() ) {
   return array_merge ( $this->Address->validate ( $data ), parent::validate ( $data ) );

User Interface

As I alluded to initially, what I really want to do is to perform server-side validation while providing the illusion of client-side validation. To do that, I employ the appropriate controller. If I’m able to submit the entire form via Ajax, this becomes trivial because the same request can perform both actions (provided no errors are reported). Here’s how it might look on a vendor application page (/vendors/apply):

public function apply() {
   $errors = $this->Vendor->validate ( $this->data );

if ( !empty ( $errors ) ) { /** Package the errors for an ajax return */ echo json_encode ( array ( ‘errors’ => $errors ); ); exit(); } /** If there are no errors…save */ exit(); }

If I want to validate first (again, via Ajax) and then submit to a different action page, all I have to do is create a validate() method in the controller, make the Ajax call to that and, if no errors are returned, submit the form to the preferred action. If errors are returned, I can use jQuery’s JSON parser to extract the messages and drop them on the screen.

With this technique, I can consolidate my validation, rarely write more than one block of code to access that validation and present the results to a user attractively without that user ever being aware that anything more than client-side error handling has been done. What technique(s) do you employ to minimize your validation headaches?