开发者

How make file field required in codeigniter

开发者 https://www.devze.com 2023-03-13 15:43 出处:网络
Codeigniter form validation support post array to validate, it does not support $_FILE array to validate.

Codeigniter form validation support post array to validate, it does not support $_FILE array to validate.

I want to validate file field as required like this rule

$rules['file'] = "trim开发者_开发百科|required";

Please help me how to make file field as required.


Hope the html code in your form would be like this :

<form method="post" action="">
    <div class="form_label">
        <label for="form_field_name">Select : </label>
        <input type="file" name="form_field_name" />
    </div>
    <div class="message"><?php echo (isset($message['error'])) ? '<div class="error">' . $message['error'] . '</div>' : (isset($message['success']) ? '<div class="success">' . $message['success'] . '</div>' : ''); ?>
</form>

Let us go to codeigniter controller :

<?php
class My_upload extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    function upload_me()
    {
        $data['message'] = array();
        if(isset($_POST['submit'])) {
            $this->load->model('my_upload_model', 'umodel');
            $data['message'] = $this->umodel->upload_me();
        }
        $this->load->view('file_upload');
    }
}
?>

No file validation on controller, let us do it in model :

<?php
class My_upload_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function upload_me()
    {
        // file upload configuration start //
        $config['file_upload_path'] = FCPATH . 'my_file_directory' . DIRECTORY_SEPARATOR . 'sub_directory' . DIRECTORY_SEPARATOR;
        $config['allowed_extensions'] = 'gif|jpg|jpeg|png|bmp';

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('form_field_name')) {
            return array('error' => $this->upload->display_errors());
        } else {
            return array('success' => 'File is uploaded successfully.');
        }
        // end file uploading //
    }
}
?>

You can add more configuration as your requirements. More here http://codeigniter.com/user_guide/libraries/file_uploading.html

Hope this will help you, let us know if anything there. please paste the code...

Thanks


Actually you can use the $_FILES array to check, I have done this multiple times in CI ?

    if (isset($_FILES)) 
    {   


Using this, you can make file field required

$this->form_validation->set_rules('userfile', 'Document', 'required');
0

精彩评论

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

关注公众号