Tag Archive CodeIgniter

Byphunsanit

Custom Rules Validation

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

\application\controllers\FormValidationCustomRules.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?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’,’ข้อความ’)