即使自定义验证规则为false,也会触发验证。为什么?

时间:2013-12-27 18:17:34

标签: cakephp

<?php
App::uses('AppModel', 'Model');

class Announcement extends AppModel {

    public $validate = array(
        'id' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                                ),
            'numeric' => array(
                'rule' => array('numeric'),
            ),
        ),
        'enabled' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            ),
            'boolean' => array(
                'rule' => array('boolean'),
            ),
        ),
        'firstPageEnterDate' => array(
            'datetime' => array(
                'rule' => 'compareDates',
                'message' => 'attention to data interval',
            ),
        ),
        'firstPageLeaveDate' => array(
            'datetime' => array(
                'rule' => array('datetime'),
            ),
            'notempty' => array(
                'rule' => array('notempty'),
            ),
        )
    );

    public function compareDates() {
        if ($this->data[$this->alias]['enabled'] == 1) {
            return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
        }
    }
}

问题是: 它显示firstPageEnterDate上设置的验证消息,无论如何 $this->data[$this->alias]['enabled'] == 1或不。{/ p>

请注意这个条件: $this->data[$this->alias]['enabled'] == 1并非总是如此。但即使它是假的,所以内部的内容也不会运行,但仍会显示消息。

所以,看起来,如果Cake看到启用了rulemessage,无论rule内是什么,它都会触发相关的验证消息!

有什么线索?

'firstPageEnterDate' => array(
            'datetime' => array(
                'rule' => 'compareDates',
                'message' => 'attention to data interval',
            ),

1 个答案:

答案 0 :(得分:1)

如果true有效,请返回compareDates(),或者如果您不想检查它,因为它会被视为有效。

public function compareDates() {
    if ($this->data[$this->alias]['enabled'] != 1) return true; // we don't want to check
    return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
}

您还可以检查beforeValidate()回调enabled的值并从那里取消设置验证规则。