RSS

Data Validation in CakePHP

12 Jun

Data validation is an important part of any application, as it helps to make sure that the data in a Model conforms to the business rules of the application. For example, you might want to make sure that passwords are at least eight characters long, or ensure that usernames are unique. Defining validation rules makes form handling much, much easier.

var $validate = array('fieldName' => 'ruleName');
<?php
class User extends AppModel {
    var $name = 'User';
    var $validate = array(
        'login' => 'alphaNumeric',
        'email' => 'email',
        'born' => 'date'
    );
}
?>

One Rule Per Field

var $validate = array(
    'fieldName1' => array(
        'rule' => 'ruleName', // or: array('ruleName', 'param1', 'param2' ...)
        'required' => true,
        'allowEmpty' => false,
        'on' => 'create', // or: 'update'
        'message' => 'Your Error Message'
    )
);
  1. Single value : 'alphaNumeric'
  2. Max, min or range : array('minLength', 15)
  3. Comparison : array(‘comparision’, ‘>’,  0.00)
  4. Number : numeric
  5. Date : date
  6. Money format : array(‘decimal’, 2)
  7. Email format : email
  8. Between 0-15 characters :  array(‘between’, 0,  15)
  9. Alphabets and Number only : alphaNumeric

Multiple Rules per Field

var $validate = array(
    'fieldName' => array(
        'ruleName' => array(
            'rule' => 'ruleName',
            // extra keys like on, required, etc. go here...
        ),
        'ruleName2' => array(
            'rule' => 'ruleName2',
            // extra keys like on, required, etc. go here...
        )
    )
);


<pre>var $validate = array(
    'login' => array(
        'loginRule-1' => array(
            'rule' => 'alphaNumeric',
            'message' => 'Only alphabets and numbers allowed',
            'last' => true
         ),
        'loginRule-2' => array(
            'rule' => array('minLength', 8),
            'message' => 'Minimum length of 8 characters'
        )
    )
);

Custom Validation Rules

Custom Regular Expression Validation

<pre>var $validate = array(
    'login' => array(
        'rule' => '/^[a-z0-9]{3,}$/i',
        'message' => 'Only letters and integers, min 3 characters'
    )
);

The example above checks if the login contains only letters and integers, with a minimum of three characters.

The regular expression in the rule must be delimited by slashes. The optional trailing ‘i’ after the last slash means the reg-exp is case insensitive.

Adding your own method

Sometimes checking data with regular expression patterns is not enough. For example, if you want to ensure that a promotional code can only be used 25 times, you need to add your own validation function, as shown below:

<pre><?php
class User extends AppModel {
    var $name = 'User';

    var $validate = array(
        'promotion_code' => array(
            'rule' => array('limitDuplicates', 25),
            'message' => 'This code has been used too many times.'
        )
    );

    function limitDuplicates($check, $limit){
        //$check will have value: array('promomotion_code' => 'some-value')
        //$limit will have value: 25
        $existing_promo_count = $this->find( 'count', array('conditions' => $check, 'recursive' => -1) );
        return $existing_promo_count < $limit;
    }
}
?>
</pre>

The current field to be validated is passed into the function as first parameter as an associated array with field name as key and posted data as value.

If you want to pass extra parameters to your validation function, add elements onto the ‘rule’ array, and handle them as extra params (after the main $check param) in your function.

Your validation function can be in the model (as in the example above), or in a behavior that the model implements. This includes mapped methods.

When writing a validation rule which can be used by multiple fields, take care to extract the field value from the $check array. The $check array is passed with the form field name as its key and the field value as its value. The full record being validated is stored in $this->data member variable.

<pre><?php
class Post extends AppModel {
  var $name = 'Post';

  var $validate = array(
    'slug' => array(
      'rule' => 'alphaNumericDashUnderscore',
      'message' => 'Slug can only be letters, numbers, dash and underscore'
      )
    );

    function alphaNumericDashUnderscore($check) {
      // $data array is passed using the form field name as the key
      // have to extract the value to make the function generic
      $value = array_values($check);
      $value = $value[0];

      return preg_match('|^[0-9a-zA-Z_-]*$|', $value);
    }
}
?>
</pre>
Advertisements
 
1 Comment

Posted by on June 12, 2010 in PHP

 

One response to “Data Validation in CakePHP

  1. Johnd93

    September 18, 2014 at 8:54 AM

    I am in agreement with pretty much everything that you mentioned entirely! Excellent website document! aakeeeekeegk

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: