cakephpcakephp-2.7

Share custom validation method between given models


I want to share validation function between multiple models. Like components in controller.

I think extending AppModel isnt an option, because the function isnt applicable to all of my Models, just 3 of them.

If possible I want to do it DRY.


Solution

  • To share methods between models in CakePHP use Behaviors (the model equivalent of controller components).

    You can do something like this to define your custom validation rules:-

    // app/Model/Behavior/ValidateBehavior.php
    class ValidateBehavior extends ModelBehavior {
        public function customValidationRule($Model, $data) {
            // some validation code
        }
    }
    
    // example model
    class Example extends AppModel {
        public $actsAs = array('Validate');
    
        public $validate = array(
            'field' => array(
                'custom' => array(
                    'rule' => array('customValidationRule')
                )
            ),
        );
    }