【问题标题】:Showing validation errors for specific input field显示特定输入字段的验证错误
【发布时间】:2013-03-20 23:35:07
【问题描述】:

我设置了一个为个人资料图片上传文件的表单,我正在验证文件上传,如下所示:

'picture' => array(
    'kosher' => array(
        'rule' => 'validateImage',
        'message' => 'Only images are allowed to be uploaded'
    ),
    'size' => array(
        'rule' => array('fileSize', '<=', '2MB'),
        'message' => 'Picture must be less than 2 MB'
    )
)

验证运行正常,但是当我提交不正确的数据时,表单上没有显示验证错误。我正在构建整个表单:

<?php echo $this->Form->create('Profile', array('type' => 'file')); ?>
<?php echo $this->Form->hidden('id'); ?>
<?php echo $this->Form->label('Profile.picture', 'Profile picture'); ?>
<?php echo $this->Form->file('picture'); ?>
<?php echo $this->Form->input('firstname'); ?>
<?php echo $this->Form->input('lastname'); ?>
<?php echo $this->Form->input('email', array('between' => 'This is the email other users will use to contact you')); ?>
<?php echo $this->Form->input('Skill', array('type' => 'text', 'value' => $skills, 'label' => 'Your skills (seperate each skill by space)')); ?>
<?php echo $this->Form->input('course'); ?>
<?php echo $this->Form->input('bio'); ?>
<?php echo $this->Form->end('Save changes'); ?>

其他字段错误消息显示正确,只是文件上传不正确。如何使验证错误显示在文件输入周围?

【问题讨论】:

  • 'picture' 被定义为&lt;?php echo $this-&gt;Form-&gt;file('picture'); ?&gt; 的数组,但不是size。据我所知。
  • 我听不懂你在说什么?
  • 'picture''firstname' 等相比,您的'size' 没有在任何地方回显。文件上传的错误消息不是'message' =&gt; 'Picture must be less than 2 MB'
  • 也许你需要在某处添加&lt;?php echo $this-&gt;Form-&gt;file('size'); ?&gt;。再说一次,我可能错了。
  • 显示“validateImage”的验证操作

标签: php validation cakephp file-upload


【解决方案1】:

您使用了$this-&gt;Form-&gt;file('picture');,它只会生成文件上传字段。

要么在其下方添加一个$this-&gt;Form-&gt;error('picture');,它将显示验证错误消息,要么使用$this-&gt;Form-&gt;input('picture', array('type' =&gt; 'file')); 来生成文件上传输入。

Form::input() 是一个包装器方法,它生成所需的输入字段、标签标签并显示验证错误消息(如果有)。请阅读手册。

【讨论】:

  • 您可能必须指定用于“图片”字段的输入类型,因为 CakePHP FormHelper 不会自动创建 file 输入;即echo $this-&gt;Form-&gt;input('picture', array('type' =&gt; 'file'));
  • 对了,忘记说了。需要指定'type' =&gt; 'file',因为它不能自动推断。我相应地更新了我的原始答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-25
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
相关资源
最近更新 更多