Tag Archive upload

Byphunsanit

Custom Rules Validation

ตัวอย่างการเขียน custom rule validation

<?php
class FormValidationCustomRules extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        // Your own constructor code
    }

    public function uploadJPEG()
    {
        $this->form_validation->set_rules('cover', 'JPEG Upload', 'trim|xss_clean');

        if ($this->form_validation->run() == true) {
            $fileDir = 'assets/contents/';
            $fileName = date('U') . '.jpeg';

            $config = [
                'allowed_types' => 'jfi|jfif|jif|jpe|jpeg|jpg',
                'file_ext_tolower' => true,
                'file_name' => $fileName,
                'max_size' => '10000',
                'overwrite' => false,
                'upload_path' => $fileDir,
            ];

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

            if ($this->upload->do_upload('cover', false)) {
                $this->uploadFile = $fileDir . $fileName;
                return true;
            } else {
                $this->form_validation->set_message('uploadJPEG', $data['error'] = $this->upload->display_errors());

                if ($_FILES['cover']['error'] != 4) {
                    return false;
                }
            }
        }

        return false;
    }

    public function index()
    {
        $this->load->library('form_validation');

        $formValidation = [
            [
                'field' => 'cover',
                'label' => 'JPEG Upload',
                'rules' => 'callback_uploadJPEG',
            ],
        ];
        $this->form_validation->set_rules($formValidation);

        if ($this->form_validation->run() == true) {
            echo 'upload file to ', $this->uploadFile, '<br><img alt="', $this->uploadFile, '" class="img-thumbnail" src="../', $this->uploadFile, '">';
        }

        $this->load->view('FormValidation/CustomRules');
    }
}

หลักการคือ

  • สร้าง function ขึ้นมา แล้วเรียกใช้โดยมี callback_ นำหน้า
  • ส่ง message กลับมาโดยใช้ $this->form_validation->set_message(‘function name’,’ข้อความ’)