CakePHP模型验证

时间:2014-06-06 13:18:39

标签: php validation cakephp

我在CakePHP中有一个简单的表单。

我想上传图片,想在recent_picture上定义CakePHP验证。

<?php echo $this->Form->create('MyController', array('type' => 'file')); ?>
<?php echo $this->Form->file('recent_picture'); ?>
<?php echo $this->Form->end(__('Create Account & Continue')); ?>

我在模型中定义了验证。

     public $validate = array(
        'recent_picture' => array(
            'rule'    => array(
            'extension',
            array('gif', 'jpeg', 'png', 'jpg')
            ),
            'message' => 'Please supply a valid image.'
        ),  
    );

如果我没有填写,则以上验证可以正常运行并给出错误。但它没有验证图像扩展。

所以请帮助我。

任何帮助都会受到赞赏。

感谢。

1 个答案:

答案 0 :(得分:0)

我不知道为什么它不起作用,因为它对我来说也不起作用(我可能跟你一样的文件)就在一两天前,而且因为挣扎我选择了一种方式。也许那不是最好的答案,而不是干净的答案,但你可以在上传之后验证扩展名:

$mime_type_correct = preg_match("/image\/*\w+/", $file_data['type']);

希望对你有所帮助。 PS:这个片段也可以派上用场:

        switch ($file_data['error']) {
        case 0:
            //no error
            break;
        case 1:
            $err_msg = __('The uploaded file exceeds the upload_max_filesize');
            $error = true;
            break;
        case 2:
            $err_msg = __('The uploaded file exceeds the MAX_FILE_SIZE from form');
            $error = true;
            break;
        case 3:
            $error_msg = __('The uploaded file was only partially uploaded.');
            $error = true;
            break;
        case 4:
            $err_msg = __('No file was uploaded.');
            $error = true;
            break;
        case 6:
            $err_msg = __('Missing a temporary folder.');
            $error = true;
            break;
        case 7:
            $err_msg = __('Failed to write file to disk.');
            $error = true;
            break;
        case 8:
            $err_msg = __('A PHP extension stopped the file upload.');
            $error = true;
            break;

        default:
            break;
    }