CodeIgniter - 表单验证和文件上载数据

Sho*_*291 8 validation codeigniter file-upload

我想知道是否有一种方法可以使用CodeIgniter 2.0中的表单验证类来验证文件的大小.我有一个包含文件输入的表单,我想做这样的事情:

$this->form_validation->set_rule('file', 'File', 
                 'file_type[image/jpeg|image/gif|image/png]|file_max_size[500]');
Run Code Online (Sandbox Code Playgroud)

我考虑扩展验证类,将其与上传类组合,并根据上传数据进行验证,但这可能非常耗时.

有没有人知道表格验证类的任何扩展会做这样的事情?

jon*_*ohn 10

文件上载类实际上有自己的一组验证规则,您可以这样设置

$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);
Run Code Online (Sandbox Code Playgroud)

(摘自CI文档)

  • 如果你将上传字段添加到验证中,但是没有给它任何验证规则(`$ this-> form_validation-> set_rules('file_to_upload','File To Upload','');`),那么你可以把上传错误消息到form_validation对象,它将自动正确显示(`$ this-> form_validation - > _ field_data ['file_to_upload'] ['error'] = $ this-> upload-> display_errors('','') ;`).在$ this-> upload-> display_errors()中需要单引号来删除通常由`display_errors()`添加的`<p> </ p>`包装器. (2认同)

小智 9

我有同样的问题.我建立了一个联系表单,允许用户上传头像并同时编辑其他信息.每个字段单独显示表单验证错误.我无法为文件输入和其他显示方案提供不同的显示方案 - 我有一个标准方法来处理显示错误.

我使用了一个控制器定义的属性和一个回调验证函数来合并任何上传错误和表单验证的错误.

这是我的代码的摘录:

# 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;
}
Run Code Online (Sandbox Code Playgroud)

注意:由于如果其他表单字段中存在任何错误,文件输入将不会重新填充,在上载成功时,我会在进行任何其他验证之前存储并更新它 - 因此用户无需重新选择该文件.如果发生这种情况,我的通知会有所不同.

  • 这是$ _FILES数组的好方法.作为您的方法的替代方法,我将文件数组检查移动到验证回调中,以便我可以运行其他验证. (2认同)