如何使用配置设置创建验证码验证规则?

时间:2014-04-14 23:48:39

标签: php cakephp

在我的博客插件中,我想创建一个验证码,用户可以在机器人学习如何解决它时进行更改。我的想法是有两个配置设置:'Plugin.Blog.captcha_answer'和'Plugin.Blog.captcha_question',以及默认情况下用户没有设置它。

然后在BlogPostComment模型中,有一个验证规则:

public $validate = array(   'captcha' => array(
        'rule' => array('custom', $captcha_a)
        , 'message' => 'Please answer the question, correctly and in lowercase.'
        , 'required' => false
        ,
    ), 
);

所以我需要在模型中实例化$ captcha_a。我是这样做的:

public $captcha_q = (isset(Configure::read('Plugin.Blog.captcha_answer'))) ?  Configure::read('Plugin.Blog.captcha_question') : "orange";

事实证明,在类变量声明期间无法调用函数。

我还能怎么做?

3 个答案:

答案 0 :(得分:0)

您可以在构造函数中设置这些变量吗?

答案 1 :(得分:0)

CakePHP在模型中有一个beforeValidate回调:

public function beforeValidate($options = array()) {
    parent::beforeValidate($options);
    $this->validate['captcha'] = array(/* your rules here */);
}

答案 2 :(得分:0)

最好的方法是将验证作为一个单独的函数,并将其传递给$ validate数组。

http://book.cakephp.org/2.0/en/models/data-validation.html#adding-your-own-validation-methods

相关问题