CakePHP验证未检测到表单字段

时间:2013-10-03 19:11:37

标签: php forms validation cakephp

我有一个用户可以上传图片的表单,我将其打印到页面上,如下所示:

<?php echo $this->Form->label('file', 'Image file', array('class' => 'col-lg-1 control-label')); ?>

然后,在模型中,我正在设置验证:

public $validate = array(
    'file' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'You must select an image to upload'
        ),
        'extension' => array(
            'rule' => array('extension', array('png')),
            'message' => 'Images must be in PNG format'
        ),
        'size' => array(
            'rule' => array('fileSize', '<', '1MB'),
            'message' => 'Images must be no larger than 1MB'
        ),
        'goodUpload' => array(
            'rule' => 'uploadError',
            'message' => 'Something went wrong with the upload, please try again'
        )
    )
);

但是,Cake似乎没有将表单字段与验证规则相关联,就像我选择要上传的图像一样,我总是得到“您必须选择要上传的图像”作为表单错误。我确保表单有enctype="multipart/form-data"

这是否因为file不是数据库字段而发生?如何在file上对蛋糕进行一些验证?

编辑:根据要求,这是我的整个表单:http://pastebin.com/SbSbtDP9

2 个答案:

答案 0 :(得分:1)

只要在正确的模型中具有正确的字段名称,就可以验证数据库中没有的字段。

从我在代码中看到的内容看来,您输出的是标签而不是实际输入,我会尝试上传图片

echo $this->Form->create('Model', array('type'=>'file'));
echo $this->Form->input('file', array('type'=>'file'));
echo $this->Form->submit('Upload Image'):
echo $this->Form->end();

对于验证,我会尝试使用其他验证选项(大小等)... CakePHP通常会在文件上载的notEmpty上抛出错误。所以只检查扩展类型通常就足够了。

public $validate = array(
   'file' => array(
     'rule' => array(
     'extension', array('jpeg', 'jpg')
     'message' => 'You must supply a file.'
     )
   )
);

CakePHP中用于图像上传的大部分时间我使用https://github.com/josegonzalez/cakephp-upload这样的插件,它可以进行验证和上传处理。

答案 1 :(得分:0)

管理解决问题。事实证明,对文件字段进行notEmpty验证时,它始终认为没有任何内容,因此总是抛出该验证消息。

通过编写我自己的验证方法来解决它。

相关问题