有没有办法验证数据(使用CakePHP的模型验证),以确保至少“a”或“b”有数据(两者都不必有数据)。
答案 0 :(得分:4)
在你的模型中,做这样的事情。执行保存操作时将调用该函数。
<强> EDITED 强>
public $validate = array(
'a' => array(
'customCheck' => array(
'rule' => 'abCheck',
'message' => 'You must enter data in a or b.'
)
),
'b' => array(
'customCheck' => array(
'rule' => 'abCheck',
'message' => 'You must enter data in a or b.'
)
)
);
//Function must be public for Validator to work
//Checks to see if either a or b properties are set and not empty
public function abCheck(){
if((isset($this->data['Model']['a']) && !empty($this->data['Model']['a'])) || (isset($this->data['Model']['b']) && !empty($this->data['Model']['b']))){
return true;
}
return false;
}
答案 1 :(得分:1)
您可以通过“自定义验证”验证这些条件。
答案 2 :(得分:0)
请改为尝试:
public $validate = array(
'a' => array(
'customCheck' => array(
'rule' => array('abCheck', 1),
'message' => 'You must enter data in a or b.'
)
),
'b' => array(
'customCheck' => array(
'rule' => array('abCheck', 1),
'message' => 'You must enter data in a or b.'
)
)
);
//Function must be public for Validator to work
//Checks to see if either a or b properties are set and not empty
public function abCheck(){
if((isset($this->data['Model']['a']) && !empty($this->data['Model']['a'])) > || (isset($this->data['Model']['b']) && !empty($this->data['Model']['b']))){
return 1;
}
return -1;
}