Cakephp如何验证数组以确保它至少包含五个或更多项

时间:2012-06-27 14:27:51

标签: cakephp cakephp-1.3 cakephp-2.0

我们需要帮助我的代码。我有一个表格,学生可以选择他们获得的科目,分数和成绩。主题和成绩是一个下拉菜单,它们处于循环中。我希望学生至少输入五门科目,包括英语。每个主题由主题代码引用。你能帮帮我吗?

我的控制器功能

subject_code' => $this->data['ApplicantOlevelQualification']['subject_code'][$i],
'grade' =>  $this->data['ApplicantOlevelQualification']['grade'][$i],

我的模型如下

public $validate = array(
'grade' => array(
        'notempty' => array(
        'rule' => array('notempty'),
        // extra keys like on, required, etc. go here...
    ),
    'ruleName2' => array(
        'rule' => array('inList', array('A', 'B','C','D','E')),
        'message' => 'Not in range.',
    ),
),
'subject_code' => array(
        'numeric' => array(
            'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
    ),

1 个答案:

答案 0 :(得分:0)

您需要创建自定义验证。

看看这里: http://book.cakephp.org/1.3/view/1179/Custom-Validation-Rules

一个例子:

<?php
class User extends AppModel {
    var $name = 'User';

    var $validate = array(
        'promotion_code' => array(
            'rule' => array('limitDuplicates', 25),
            'message' => 'This code has been used too many times.'
        )
    );

    function limitDuplicates($check, $limit){
        //$check will have value: array('promomotion_code' => 'some-value')
        //$limit will have value: 25
        $existing_promo_count = $this->find( 'count', array('conditions' => $check, 'recursive' => -1) );
        return $existing_promo_count < $limit;
    }
}
?>