2009-09-03 169 views

回答

6

A 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; 
} 
+0

这是可怕的,我几乎写了完全相同的代码行为线,几天前? – brndnmg 2009-09-07 05:56:05

+0

只有这么多理智的方法才能做到这一点......) – deceze 2009-09-07 05:57:18

+1

我想说明的是,您需要allowEmpty = null作为所有规则。否则,该规则将被忽略(allowEmpty = true),或者未执行而失败(allowEmpty = false)。如果你不考虑这个问题,它可能会令人困惑:)。 – 2011-06-03 11:25:22

0

您可能需要使用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(); 
} 

祝你好运!

+0

+1我同意在模型中使用beforeValidate。您也可以设置一个字段名称数组并循环。如果你有超过3-4个你正在查看的领域,这将特别有用。 – Dooltaz 2009-09-03 16:37:20

+0

这种方法的问题是破坏了正常的验证过程,并且除非和直到四个“特殊字段”验证,否则您将不会得到相同表单中其他字段的错误消息。 – deceze 2009-09-04 08:29:31

+0

deceze - true,但如果您需要显示特定于字段的错误消息,则添加对invalidate()的调用将会很微不足道。 – inkedmn 2009-09-04 20:40:41

相关问题