必须填写至少一个字段,cakephp验证

时间:2009-09-03 12:02:15

标签: cakephp

我有4个可选字段,但必须填写至少1个字段(任何字段)?

任何简单的方法吗?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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(); 
}
祝你好运!