Take the 2-minute tour ×

I want to add a custom validation rule that can be reused across the application when necessary. Where is the best place to put it?

I know I can put them in AppModel but it's messy and pollutes/bloats the AppModel with methods that are only used occasionally for validation, and I find I need to prefix them all with validateUsername, validateCustom, etc. to keep them clearly organised from the other methods in the AppModel. I feel like there is a better way of doing this in the OOP structure.

Is there a way to specify custom rules as static methods of a Lib class, for example?



class Validate {

    public function username($value) {
        $value = array_shift($value);
        return preg_match('/^[A-Z0-9_-]+$/i', $value);

And then use the rules only in the models when you need to:


App::uses('Validate', 'Lib');

class MyModel extends AppModel {

    public $validate = array(
        'username' => array(
            'rule' => 'Validate::username',
            'message' => 'Username contains invalid characters'
share|improve this question
I usually have them directly in my MyModel. But yeah, a own lib class would be cleaner. Careful, though: Validate as classname is already used by the core. You need MyValidate etc for cake2.x –  mark Jun 23 '13 at 21:32
You could also make a plugin of it in it's own repository and simply include that plugin the whatever app you need. That way you can reuse it. –  Jelmer Jun 23 '13 at 22:27
add comment

1 Answer

up vote 0 down vote accepted

You could do this with a Behavior. http://book.cakephp.org/2.0/en/models/behaviors.html There is a setup callback you could use to attach validation rules or create your own custom functions. You can then attach the Behaviors as needed to models.

share|improve this answer
add comment

Your Answer


