custom validation in CakePHP

Suppose there is a table ‘categories’. We want to validate the ‘category_name’ field. Category name should not be empty and the length of the name has to be 5 to 10 characters.
Then we have to make a model Category.php :

class Category extends AppModel {
var $name = “Category”;
var $validate = array(
‘category_name’ => array(
‘required’ => array(
‘rule’=>VALID_NOT_EMPTY,’message’=>’Please enter category name’),
‘length’ => array(
‘rule’ => ‘validateLength’,
‘min’ => 5,
‘max’ => 10,
‘message’=>’Category name must be of 5-10 characters.’)

function validateLength($value, $params = array()) {
$valid = false;
if ($value[‘category_name’] != ”) {
if (strlen($value[‘category_name’]) < $params[‘min’] || strlen($value[‘category_name’]) > $params[‘max’]) {
$valid = false;
} else {
$valid = true;
} else {
$valid = true;
return $valid;

Now if we leave the category name field blank, and press Submit button, it will give the error message ‘Please enter category name’. If we enter less than 5 characters or more than 10 characters in the category name field, it will show the error message ‘Category name must be of 5-10 characters.‘


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s