【问题标题】:CakePHP validation not detecting form fieldCakePHP 验证未检测到表单字段
【发布时间】:2013-10-03 19:11:36
【问题描述】:

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

<?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 不是数据库字段吗?如何让 cake 在 file 上运行验证?

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

【问题讨论】:

标签: php forms validation cakephp


【解决方案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 之类的插件,它将验证和上传处理合二为一。

【讨论】:

  • 他的代码中有$this-&gt;Form-&gt;form(...)。不需要对数据库中没有的字段做一些特殊的事情吗?
  • 没有,但是他的 Form->create 需要 options 数组中的 'type'=>'file'。
  • 好的,刚刚看了一下pastebin,由于无法对原问题添加评论,所以在这里评论!该死的低代表:(如果您将 $this->Form->file(); 更改为 $this->Form->input('file', array('type'=>'file')); 会怎样?验证?
【解决方案2】:

设法弄明白了。结果证明对文件字段进行notEmpty 验证永远不会起作用,它总是认为那里什么都没有,因此总是抛出该验证消息。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2011-03-21
    相关资源
    最近更新 更多