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

时间:2014-01-28 10:52:31

标签: cakephp

如果有字段data['Form']['gender'] then if 'female',则then ['Form']['is_pregnant']必须为'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;

}

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

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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;
}