Skip to content
This repository has been archived by the owner on Jan 15, 2021. It is now read-only.

Commit

Permalink
Initial commit of AutoValidateBehavior.php
Browse files Browse the repository at this point in the history
  • Loading branch information
Florian Krämer committed Jul 24, 2013
1 parent ba1e6e3 commit f87b7ac
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions Model/Behavior/AutoValidateBehavior.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php
App::uses('ModelBehavior', 'Model');

/**
* AutoValidateBehavior
*
* @author Florian Krämer
* @copyright 2013 Florian Krämer
* @license MIT
*/
class AutoValidateBehavior extends ModelBehavior {

/**
* beforeValidate
*
* @param Model $Model
* @return boolean
*/
public function beforeValidate(Model $Model) {
$this->generateValidationRules($Model);
return true;
}

/**
* generateValidationRules
*
* @param Model $Model
* @param array
* @return void
*/
public function generateValidationRules(Model $Model) {
$schema = $Model->schema();
foreach ($schema as $field => $meta) {
if ($field === $Model->primaryKey) {
continue;
}

if ($meta['null'] === false) {
$Model->validate[$field]['notEmpty'] = array(
'rule' => 'notEmpty',
'empty' => false,
'message' => __('This field can not be empty.'),
);
}

if ($meta['type'] === 'boolean') {
$Model->validate[$field]['boolean'] = array(
'rule' => 'boolean',
'empty' => false,
'message' => __('This field can not be empty.'),
);
}

if ($meta['type'] === 'string') {
$Model->validate[$field]['length'] = array(
'rule' => array('length', $meta['length']),
'empty' => false,
'message' => __('This field can not be longer than %d.', $meta['length']),
);
}
}
}

}

0 comments on commit f87b7ac

Please sign in to comment.