在CakePHP中使用自定义验证函数检查依赖字段

在CakePHP中使用自定义验证函数检查依赖字段,cakephp,Cakephp,如果有一个字段数据['Form']['gender']那么如果是'female',那么['Form']['is_prevented']必须是'yes'或者'no' public $validate = array( 'is_pregnant' => array( 'rule' => array('checkGender', 'female'), 'message' => 'If female, please answer if pr

如果有一个字段
数据['Form']['gender']
那么如果是'female'
那么['Form']['is_prevented']
必须是
'yes'
或者
'no'

public $validate = array(
    'is_pregnant' => array(
        'rule'    => array('checkGender', 'female'),
        'message' => 'If female, please answer if pregnant.'
    )
);

public function checkGender($check, $gender) {
    if($check == $gender)
       return true;
    else
       return false;

}

我认为我上面所做的是不对的。也许是走错了路。我还试图将其转换为一个通用函数,其中如果
field2
值是
a
,则field1值必须是
[x,y,z]

试试这样的方法:

public $validate = array(
    'is_pregnant' => array(
        'rule'    => array('checkGender'),
        'message' => 'If female, please answer if pregnant.'
    )
);


public function checkGender() {
    if($this->data[$this->alias]['gender'] == 'female' && empty($this->data[$this->alias]['is_pregnant'])) {
       return false;
    }
    return true;
}