CodeIgniter-表单验证和文件上载数据
我想知道是否有一种方法可以使用CodeIgniter 2.0中的表单验证类来验证文件的大小。我有一个包含文件输入的表单,我想做如下操作:CodeIgniter-表单验证和文件上载数据,codeigniter,file-upload,validation,Codeigniter,File Upload,Validation,我想知道是否有一种方法可以使用CodeIgniter 2.0中的表单验证类来验证文件的大小。我有一个包含文件输入的表单,我想做如下操作: $this->form_validation->set_rule('file', 'File', 'file_type[image/jpeg|image/gif|image/png]|file_max_size[500]'); 我考虑扩展验证类,将其与upload类结合起来,并基于upload数据进行验证,但这
$this->form_validation->set_rule('file', 'File',
'file_type[image/jpeg|image/gif|image/png]|file_max_size[500]');
我考虑扩展验证类,将其与upload类结合起来,并基于upload数据进行验证,但这可能会很耗时
是否有人知道表单验证类的任何扩展可以执行类似的操作?文件上载类实际上有自己的验证规则集,您可以这样设置
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
我也有同样的问题。我建立了一个联系人表单,允许用户上传一个头像,同时编辑其他信息。表单验证错误分别显示在每个字段中。我无法为文件输入和其他输入提供不同的显示方案-我有一个标准方法来处理显示错误 我使用了一个控制器定义的属性和一个回调验证函数来合并任何上传错误和表单验证错误 以下是我的代码摘录:
# controller property
private $custom_errors = array();
# form action controller method
public function contact_save()
{
# file upload for contact avatar
$this->load->library('upload', array(
'allowed_types'=>'gif|jpg|jpeg|png',
'max_size'=>'512'
));
if(isset($_FILES['avatar']['size']) && $_FILES['avatar']['size']>0)
{
if($this->upload->do_upload('avatar'))
{
# avatar saving code here
# ...
}
else
{
# store any upload error for later retrieval
$this->custom_errors['avatar'] = $this->upload->display_errors('', '');
}
}
$this->form_validation->set_rules(array(
array(
'field' => 'avatar',
'label' => 'avatar',
'rules' => 'callback_check_avatar_error'
)
# other validations rules here
);
# usual form validation here
if ($this->form_validation->run() == FALSE)
{
# display form with errors
}
else
{
# update and confirm
}
}
# the callback method that does the 'merge'
public function check_avatar_error($str)
{
#unused $str
if(isset($this->custom_errors['avatar']))
{
$this->form_validation->set_message('check_avatar_error', $this->custom_errors['avatar']);
return FALSE;
}
return TRUE;
}
注意:由于如果其他表单字段中有任何错误,文件输入将不会重新填充,因此在上载成功时,我会在进行任何其他验证之前存储并更新文件-因此用户无需重新选择文件。如果发生这种情况,我的通知会有所不同。我通常先验证表单,如果一切正常,我会开始检查文件上载的有效性。如果文件不符合验证配置,是否会更新表单验证错误?例如,如果文件太大,validation\u errors()函数是否会显示这样的错误消息?不,您必须单独处理文件上载错误,因此首先我会检查输入字段validation,然后检查
do\u upload()
,并且有一个函数专门显示上载验证错误。这些都在我在回答中链接到的文档中。如果您将上载字段添加到验证中,但不给它任何验证规则($this->form\u validation->set\u rules('file\u to\u upload'、'file to upload'、'');
),那么您可以将上载错误消息放入form\u validation对象中,它将自动正确显示($this->form_validation->_field_data['file_to_upload']['error']=$this->upload->display_errors('',)
)。在$this->upload->display_errors()中必须使用单引号来删除通常由display_errors()添加的包装
。这是使用$\u FILES数组的一个很好的技巧。作为您方法的替代方法,我将文件数组签入验证回调,以便可以使用其他验证运行。