开发者

How to use form validation with the file uploader to make sure a file is uploaded

开发者 https://www.devze.com 2023-04-12 16:25 出处:网络
Can anyone suggest how using the form validation rules I can say the following:- If no file is uploaded - then create a rule to say \'no file uploaded\' using the form validator library.

Can anyone suggest how using the form validation rules I can say the following:-

If no file is uploaded - then create a rule to say 'no file uploaded' using the form validator library.

I am using CodeIgniter 2.

For instance - it is simple to validate on a text input field using the following, but I cannot understand how this is 开发者_如何学Godone with upload (that uses the $_FILES array rather than $_POST)

eg. $this->form_validation->set_rules('title', 'Title', 'required'); // input field named 'title' is required


CodeIgniter's File Uploading class handles its own validation - no need to use the Form Validation class.

Per the documentation,

$this->upload->display_errors()


Retrieves any error messages if the do_upload() function returned false. The function does not echo automatically, it returns the data so you can assign it however you need.

In your example above, if the file input is left empty, $this->upload->display_errors() will return the following:

You did not select a file to upload.

So, set your preferences (see the "Setting Preferences" section of the documentation for exactly what is available):

// The following are just examples from the documentation...
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
// ... other preferences as necessary

If any of the above fail during the attempted upload, $this->upload->display_errors() will retrieve the appropriate error message. Simply pass it to your view to display the error(s).

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号