cakePHP 文件上传的可选验证 [英] cakePHP optional validation for file upload

查看:35
本文介绍了cakePHP 文件上传的可选验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过验证使文件上传成为可选?即使我没有选择任何文件,下面的代码也会验证.仅当我选择了文件时,我才想检查扩展名.如果我没有选择任何文件,它不应返回任何验证错误.

How to make file uploading as optional with validation? The code below validates even if i didn't selected any file. I want to check the extension only if i selected the the file. If i am not selecting any file it should not return any validation error.

class Catalog extends AppModel{
    var $name = 'Catalog';
    var $validate = array(
        'name' => array(
            'rule' => '/^[a-z0-9 ]{0,}$/i',
            'allowEmpty' => false,
            'message' => 'Invalid Catalog name'
        ),
        'imageupload' => array(
            'rule' => array('extension',array('jpeg','jpg','png','gif')),
            'required' => false,
            'allowEmpty' => true,
            'message' => 'Invalid file'
        ),
       );
}

提前致谢

推荐答案

"我分配 $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"

"I assign $this->data['Catalog']['image'] = $this->data['Catalog']['imageupload']['name'];"

所以当你保存你的数据数组时,我假设它看起来像这样:

So by the time you save your data array, it looks something like this I assume:

array(
    'image' => 'foobar',
    'imageupload' => array(
        'name' => 'foobar',
        'size' => 1234567,
        'error' => 0,
        ...
     )
)

这意味着,imageupload 验证规则正在尝试处理此数据:

Which means, the imageupload validation rule is trying to work on this data:

array(
    'name' => 'foobar',
    'size' => 1234567,
    'error' => 0,
    ...
 )

即它试图验证的值是一个数组,而不仅仅是一个字符串.这不太可能通过指定的验证规则.它也可能永远不会空".

I.e. the value it's trying to validate is an array of stuff, not just a string. And that is unlikely to pass the specified validation rule. It's also probably never "empty".

要么创建可以处理此数组的自定义验证规则,要么在尝试验证之前需要在控制器中进行更多处理.

Either you create a custom validation rule that can handle this array, or you need to do some more processing in the controller before you try to validate it.

这篇关于cakePHP 文件上传的可选验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆