July 29, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Forms Validation with CakePHP

  • November 6, 2006
  • By Jason Gilmore
  • Send Email »
  • More Articles »

In the first installment of this occasional series introducing CakePHP, I extolled the virtues of web frameworks by showing you just how CakePHP can automate the implementation of CRUD (Create, Read, Update, and Delete) interfaces. This is a great example of how a framework can greatly decrease development time, because CRUD interfaces are immensely useful no matter what sort of application you're building, are implemented in very much the same way each time, yet are very tedious and time-consuming to implement. Validation of user input is another task that follows this pattern: it's a required part of all applications, yet is a really unexciting and annoying part of the development process.

But neglecting to validate user input is akin to foregoing any defensive gameplan for containing the NFL's leading rusher. Come Sunday, chances are you're going to get run over, and perhaps even seriously hurt. Yet even in spite of the dire ramifications of doing otherwise, many developers choose to ignore the potential problems presented by user input, reasoning that data validation is tedious and distracts them from the larger goal of building a working application. The result? Corrupt and incorrect data, cross-site scripting and SQL injection attacks, and a giant headache come Monday morning.

There really is no way around it anymore: you must validate user input within every web application. However, because data validation is like scaffolding in that it's a task faced by all developers, and it follows a fairly rigorous specification regardless of where its ultimately applied, the task seems suitable for automation by a framework. CakePHP does exactly this, going a long way towards making data validation a snap. In this installment, I'd like to show you another way frameworks can make your life easier by demonstrating CakePHP's data validation capabilities.

CakePHP's Default Validators

CakePHP offers several default validators capable of ensuring a value is a valid email address (VALID_EMAIL), year (VALID_YEAR), number (VALID_NUMBER), or non-empty (VALID_NOT_EMPTY). You can attach a validator to a data model by mapping it to a corresponding schema value through an array named $validate, which is then assigned as an attribute within the appropriate model class. These mappings will be executed upon any attempt to insert or modify data tied to that model. For example, suppose you added the field number to the player model for representing the player's jersey number. Clearly only numbers should be allowed, so the VALID_NUMBER validator is mapped to the number field, like so:

<?php

class Team extends AppModel
{

  var $name = 'Team';
  var $displayField = 'name';

  var $validate = array(
    'number' => VALID_NUMBER
  );

}

?>

Once added, only numeric values will be accepted when inserting or modifying the data residing in the number field.

Custom Validators

While CakePHP's default validators are useful, typically you'll require quite a few other mechanisms for enforcing constraints. To do so, CakePHP allows you to create any conceivable validator using Perl-compatible regular expressions. For instance, all NFL football team names consist solely of alphabetical characters and a space between the location and moniker. So for example "Pittsburgh Steelers" and "Ohio State Buckeyes" are valid names, while "PittRulez 43" and "OSU#1Champs" are not. To implement this rule, you'll need to modify the Team model as was done above, but this time creating a simple regular expression which allows only alphabetical characters and spaces to be entered:

<?php

class Team extends AppModel
{

  var $name = 'Team';
  var $displayField = 'name';

  var $validate = array(
    'name' => '/^[a-zA-Z ]+$/'
  );

}

?>

Custom Error Messages

CakePHP's scaffolding infrastructure offers only a single, static error message should the user attempt to enter invalid data, stating "Please correct errors below". Savvy users might be able to quickly deduce the nature of the problem, but it might be beneficial to provide general end users with some additional direction. To modify the scaffold's default output, you'll need to override the desired view by modifying the appropriate controller and creating a new view. What's great about CakePHP's scaffolding system is the ability to selectively override actions/views, allowing you to continue taking advantage of the scaffolding system while continuing to tweak and override its components. For example, the following listing presents a modified teams_controller.php file which takes over the team addition behavior:

<?php

class TeamsController extends AppController
{
  var $scaffold;

  function add()
  {
    if (empty($this->data))
    {
      $this->render();
    }
    else
    {
      if ($this->Team->save($this->data))
      {
        $this->set('userMessage', 'Team successfully added!');            
      }
      else
      {
         $this->set('userMessage', 'Please correct the below errors.');
         $this->render();
      }
    }   
  }
}

?>

Next up is the modified add view (add.thtml), which will display a custom error message should a user attempt to insert a team name which doesn't conform to the rules defined earlier in this tutorial.

<h1>Add a team</h1>

<?php 
   if (! empty($userMessage))
      echo $userMessage;
?>
         
 <form action="<?php echo $html->url('/teams/add')?>" method="post">
   
 <div>
     
     <p>Team Name:
         
     <?php echo $html->input('Team/name', array('size'=>'40'))?>
     <?php echo $html->tagErrorMsg('Team/name', 'Team names can only consist of alphabetical
characters and spaces.')?> </p> <p><?=$html->submit('Save')?></p> </div> </form>

Once in place, any unsuccessful attempts to insert invalid forms data will produce error output as shown in the following screenshot:

As this tutorial demonstrates, frameworks such as CakePHP can handle even the most tedious aspects of web application development, user input validation included. You're left with no more excuses, validate that data!

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) is the open source editor for Apress. He's the author of the best-selling "Beginning PHP and MySQL 5, Second Edition" (Apress, 2006. 904pp.). Along with Robert Treat, Jason is the co-author of "Beginning PHP 5 and PostgreSQL 8: From Novice to Professional". Jason loves hearing from readers, so don't hesitate to write him at wjATwjgilmore.com.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel