对多个字段应用相同的验证规则


Apply same validation rule for multiple fields

如何在2.0中对50个字段应用相同的验证规则

我对不同字段重复规则不感兴趣

public $validate = array(
    'company' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Cannot be Empty',
        ),
    ),
    // rule for other 50 fields....
);

可能的解决方案:

$validate_items = array('company', 'other', 'one_more');
$validate_rule = array(
    'notempty' => array(
        'rule' => array('notempty'),
        'message' => 'Cannot be Empty')
    );
$validate = array();
foreach ($validate_items as $validate_item) {
    $validate[$validate_item] = $validate_rule;
}
echo "<pre>".print_r($validate, true)."</pre>";

不明白为什么你要确定相同的验证50次。你可以只声明一条规则,并将其用于所有字段。

我可能误解了你的问题吧?

您可以在控制器中执行保存之前动态构建您的$validate规则:

add() {

if (!empty($this->request->data) {
    $validate = array();
    foreach($fields as $field) {
        $validate[$field] = array(
            'required'=>array(
                'rule'='notEmpty',
                'message'=>'Cannot be empty'
            )
        );
    }
    $this->ModelName->validate = $validate;
    if (!$this->ModelName->save($this->request->data)) {
       // didn't save
    }
    else {
       // did save
    }
}

}

其中$fields是一个数组,包含要应用验证的字段列表。

理想情况下,您应该将构建验证数组的代码转移到模型中,但效果是相同的

您可以应用相同的技术来允许您为一个模型拥有多个验证规则。

新示例:

$fields_to_check = array('company', 'field_2', 'field_5'); // declare here all the fields you want to check on "not empty"
$errors = 0;
foreach ($_POST as $key => $value) {
    if (in_array($key, $fields_to_check)) {
        if ($value == "") $errors++;
    }
}
if ($errors > 0) echo "There are ".$errors." errors in the form. Chech if all requered fields are filled in!"; //error! Not all fields are set correctly
else //do some action