2

I'm wondering what's the "best" approach to validate fields generically. In my application several tables have date values that are always entered using a date picker widget. I don't want to repeat the validation code, so I would like to do something like filling the $validate array in the AppModel. But it gets overwritten in the concrete model class. The best I found so far is the paragraph "Dynamically change validation rules" in the cake book, and apply that logic to the AppModel somehow, but it looks a bit hacky and un-caky. Does anyone have a hint? (If you have questions, please ask.) Thanks

4

2 回答 2

0

只是以不同的方式命名它们 - 可以说是独一无二的:

public function validateDateTime() {}

等等。这样你的自定义规则就不会重写核心规则,反之亦然。

于 2013-08-18T12:03:07.263 回答
0

我有一些验证规则,我想放入 3 个模型中,不要重复相同的代码,这就是我所做的

在 AppModel.php 中,使用应该在多个模型中的规则定义一些 var。

public $validationRules = arra(
  // rules here
);

并在 AppModel 的构造函数中为必要的模型添加它们

public function __construct($id = false, $table = null, $ds = null) {
    parent::__construct($id, $table, $ds);

    /**
     * add validation
    */
    if (in_array($this->alias, array('MyModel1', 'MyModel2', 'MyModel3')) ) {
        $this->validate = array_merge($this->validate, $this->validationRules);
    }
}

如果有一些自定义验证函数,也可以将它们移到 AppModel.php 中。

于 2015-01-03T21:01:42.360 回答