Cakephp:根据从下拉列表中选择的选项验证输入字段



嗨,伙计们,我需要代码方面的帮助,我不知道该怎么做。我有一个表格,学生选择一个考试机构,如果选择的考试机构是 zimsec,分数应该是空的,如果考试主体是剑桥,分数不应该是空的,应该根据成绩取一个范围。validMarks是我用来验证标记的函数,当我允许标记为空以适应Zimsec时,它停止工作。

我的添加.ctp

echo "<td>"; 
echo $this->Form->label('Mark(%): ');
echo "</td><td>";   
echo $this->Form->input("ApplicantOlevelQualification.mark.$s",array('label'=>''));
echo "</td></tr>";
echo $this->Form->label('Exam Body<font color=red>*</font>');
$exambody=array(
    'ZIMSEC'=>'ZIMSEC',
    'CAMBRIDGE'=>'CAMBRIDGE'
);
echo $this->Form->select('exam_body_code',$exambody,array('empty'=>'Please Select','selected'=>false,'label'=>'Exam Body<font color="red">*</font>'));

我的控制器

$exam_body_code = $this->data['ApplicantOlevelQualification']['exam_body_code'];
'mark' => $this->data['ApplicantOlevelQualification']['mark'][$i],

我的模型

'exam_body_code' => array(
    'notempty' => array(
        'rule' => array('notempty'),
    ),
),
'mark' => array(
    //'numeric' => array(
    //'rule' => array('numeric'),
    'rule' => array('validMarks'),
        'message' => 'Wrong mark for this grade, please try again.',
        'allowEmpty' => true,
    //  ),
),
public function validMarks($check) {
    $grade=($this->data['ApplicantOlevelQualification']['grade']);
    $mark=($this->data['ApplicantOlevelQualification']['mark']);
    //var_dump($mark);
    if($grade== 'A' && $mark>74) {
        // $this->validationError( 'grade', 'Grade A must be greater than or equal to 75%' );
        //Access $this->data and $check to compare your marks and grade;
        return true;
    } elseif( ($grade)== 'B' && ($mark>64)) {
        return true;   
    } elseif( ($grade)== 'C' && ($mark)>50) {
        return true;   
    } elseif( ($grade)== 'D' && ($mark)>40) {
        return true;   
    } elseif( ($grade)== 'E' && ($mark)>30) {
        return true;   
    } elseif( ($grade)== 'U' && ($mark)>0) {
        return true;   
    } else {
        return false;
    }
    //Access $this->data and $check to compare your marks and grade..
 }
如果

选择的考试机构是ZIMSEC,则分数应为空,如果考试主体为剑桥,则分数不应为空,应取一个范围...

在这种情况下,您应该将验证拆分为 2 个函数:

function emptyIfZimsec($data) {
    return $this->data['ApplicantOlevelQualification']['exam_body_code'] != 'ZIMSEC'
        || empty($this->data['ApplicantOlevelQualification']['mark']);
}
function validMarks($data) {
    if ($this->data['ApplicantOlevelQualification']['exam_body_code'] != 'CAMBRIDGE')
        return true;
    ...
如果代码为 ZIMSEC

且标记不为空,emptyIfZimsec将导致验证错误。 validMarks将检查剑桥标记(如果 ZIMSEC 则跳过)

这样,您还可以为每个案例输出单独的验证错误消息。

希望这有帮助。

最新更新