【发布时间】:2009-09-03 12:02:14
【问题描述】:
我有 4 个可选字段,但至少 1 个字段(任意字段)必须填写?
有什么简单的方法吗?
【问题讨论】:
标签: cakephp
我有 4 个可选字段,但至少 1 个字段(任意字段)必须填写?
有什么简单的方法吗?
【问题讨论】:
标签: cakephp
custom validation rule 是要走的路!
var $validate = array(
'myField1' => array('atLeastOne'),
'myField2' => array('atLeastOne'),
'myField3' => array('atLeastOne'),
'myField4' => array('atLeastOne')
);
function atLeastOne($data) {
return !empty($this->data[$this->name]['myField1'])
|| !empty($this->data[$this->name]['myField2'])
|| !empty($this->data[$this->name]['myField3'])
|| !empty($this->data[$this->name]['myField4']);
}
您还可以传入要比较的所有字段的额外参数,并从中制作更通用的功能。
var $validate = array(
'myField1' => array('atLeastOne', 'myField2', 'myField3', 'myField4'),
...
);
// just pulled out of thin air (i.e. untested)
function atLeastOne($data) {
$args = func_get_args(); // will contain $data, 'myField2', 'myField3', ...
foreach ($args as $name) {
if (is_array($name)) {
$name = current(array_keys($name));
}
if (!empty($this->data[$this->name][$name])) {
return true;
}
}
return false;
}
【讨论】:
您可能需要使用beforeValidate() 回调手动实现验证。示例(在您的模型中,我们将其称为 Item):
function beforeValidate(){
$valid = false;
if(!empty($this->data['Item']['foo'])){
$valid = true;
}
// do that same thing for the other three fields, setting $valid to true if any of the fields has a value.
return $valid && parent::beforeValidate();
}
你也可以像这样做一个长的比较作业,但我发现这种废话真的很难阅读:
function beforeValidate(){
$valid = !empty($this->data['Item']['foo']) || !empty($this->data['Item']['bar']) || !empty($this->data['Item']['baz']) || !empty($this->data['Item']['bling'])
return $valid && parent::beforeValidate();
}
祝你好运!
【讨论】:
beforeValidate 回调旨在为验证准备数据,而不是验证它。 book.cakephp.org/view/682/beforeValidate