如何验证可选字段和"允许空"当该字段在cakephp 2.x中有多个规则时

时间:2015-02-06 10:15:01

标签: cakephp cakephp-2.0

我想允许注册用户上传他们的照片。 即使我允许所有规则都为空并且将required设置为false,也始终需要输入文件。

在我看来add.ctp我有文件输入的这部分代码

<fieldset>
<legend>Photographie</legend>
<?php
    echo $this->Form->input('photo', array(
        'label' => false,
        'wrapInput' => 'col-md-9 col-md-offset-3',
        'class' => false,
        'type' => 'file',
        'beforeInput' => '<div class="input-group"><span class="input-group-btn"><span class="btn btn-default btn-file"><i class="fa fa-image"></i> Télécharger votre photo',
        'afterInput' => '</span></span><div class="form-control file-name"></div></div><span class="help-block">Fichier image uniquement, 2Mo maximum (jpg, gif, jpg)</span>',
    ));
?>
</fieldset>

模型中的验证规则如下:

public $validate = array(
    'photo' => array(
        'rule2' => array(
            'rule' => array('isMime', array('image/jpeg', 'image/gif', 'image/png')),
            'message' => 'Mime type incorrect.',
            'allowEmpty' => true,
            'required' => false,
        ),
        'rule3' => array(
            'rule' => array('isExtension', array('jpg', 'jpeg', 'gif', 'png')),
            'message' => 'Incorrect extension.',
            'allowEmpty' => true,
            'required' => false,
        ),
        'rule4' => array(
            'rule' => array('isBelowFileSize', '2097152'),
            'message' => 'File size over limit',
            'allowEmpty' => true,
            'required' => false,
        ),
    )
);

public function isMime($check, $mimeTypes) {
    $file = array_shift($check);
    if (in_array($file['type'], $mimeTypes)) {
        return true;
    }
    return false;
}

public function isExtension($check, $extensions) {
    $file = array_shift($check);
    $extension = substr(strrchr($file['name'], '.'), 1);
    if (in_array($extension, $extensions)) {
        return true;
    }
    return false;
}

public function isBelowFileSize($check, $limit) {
    $file = array_shift($check);
    if ($file['size'] <= $limit) {
        return true;
    }
    return false;
}

0 个答案:

没有答案