Kategori
PHP

Form Validation on CodeIgniter

Case Study : Create a Form and its validation with CodeIgniter.

System Requirements : CodeIgniter PHP Framework, download here. And Webserver Package.

User Requirements : PHP skills, Mysql skills, HTML skills, and (few, enough) CodeIgniter skills.

When developing a web application, like it or not sure we will often use a form. Form is very useful to make an interface for inputing data into the database. In order to prevent the data input that saved to database is correct, or desirable, we need a validation. In PHP programming language, in general, validation is made by using the ereg functions, using regular expression (regex). And believe me, regex is very complicated. Hahahah

With CodeIgniter, validation is much easier to make when compared with normal php.

Ohya, this is a server-side validation. Clearly, validation is performed from the server side so that automatic validation system will be more secure than the client-side validation (usually made with javascript)

Okay, here we go…

Step 1 : CI Configuration

  1. Open the config.php file located in the system-application-config-config.php folder
  2. Change base url, adjust to the location where your CI folders are (ci extract folder). For example : Your CI folder is in the www/ciso change the line $config['base_url']="http://example.com/";
    with
    $config['base_url'] = "http://localhost/ci/";
  3. Database setting. Open database.php file located in the same folder with config.php. Change hostname, username, password, dan nama database. Adjust according your Mysql setting. For Example :$db['default']['hostname'] = "localhost";
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "db_code";

Step 2 : Prepare the database

  1. Create a database with name db_code (via phpmyadmin)
  2. Prepare a table with name tb_student (for the structure, see picture below)

    tb_student's structure
  3. Ok, we’re done with database !

Step 3 : Make Controller

  1. Type the following script with your favorite text editor
    <?php
    class Student extends Controller {function Student(){
    parent::Controller();
    $this->load->library(array('table','validation'));
    $this->load->helper('url');
    }
    function index() {
    $this->_set_fields();
    $data['title'] = 'Add New Student';
    $data['message'] = '';
    $data['action'] = site_url('student/addStudent');
    $this->load->view('addStudent_view', $data);
    }
    function addStudent(){
    $data1['title'] = 'Add New Student';
    $data1['action'] = site_url('student/addStudent');
    $this->_set_fields();
    $this->_set_rules();
    // run the validation
    if ($this->validation->run() == FALSE){
    $data['message'] = '';
    }else{
    // saving data
    $data= array('id' => $this->input->post('id'),
    'nama' => $this->input->post('nama'),
    'email' => $this->input->post('email')
    );
    $this->db->insert('tb_student', $data);
    $data1['message'] = 'Sukses';
    }
    // load view
    $this->load->view('addStudent_view', $data1);
    }
    function _set_fields(){
    $fields['id'] = 'id';
    $fields['nama'] = 'nama';
    $fields['email'] = 'email';
    $this->validation->set_fields($fields);
    }
    // rules for validation
    function _set_rules(){
    $rules['id'] = 'trim|required|numeric';
    $rules['nama'] = 'trim|required';
    $rules['email'] = 'trim|required|valid_email';
    $this->validation->set_rules($rules);
    $this->validation->set_message('required', '* required');
    $this->validation->set_message('numeric', '* numeric only');
    $this->validation->set_message('valid_email', '* email not valid');
    $this->validation->set_error_delimiters('<p>', '</p>');
    }
    }
    ?>
  2. Save in the system-application-controllers folder, with the name student.php

Step 4 : Create View

  1. Type the script below,
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Form Validation CI</title>
    </head>
    <body>
    <h1><?php echo $title; ?></h1>
    <?php if (isset($message)) echo $message; ?>
    <form method="post" action="<?php echo $action; ?>">
    <table>
    <tr>
    <td valign="top">ID*</td>
    <td><input type="text" name="id" value="<?php echo $this->validation->id; ?>"/>
    <span style="color:red;"> <?php echo $this->validation->id_error; ?></span></td>
    </tr>
    <tr>
    <td valign="top">Nama<span style="color:red;">*</span></td>
    <td><input type="text" name="nama" value="<?php echo $this->validation->nama; ?>"/>
    <span style="color:red;"> <?php echo $this->validation->nama_error; ?></span></td>
    </tr>
    <tr>
    <td valign="top">Email<span style="color:red;">*</span></td>
    <td><input type="text" name="email" value="<?php echo $this->validation->email; ?>"/>
    <span style="color:red;"> <?php echo $this->validation->email_error; ?></span></td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td><input type="submit" value="Save"/></td>
    </tr>
    </table>
    </form>
    </body>
    </html>
  2. Save in the system-application-views folder, with the name addStudent_view.php

Step 5 : Testing Code

  1. Open your browser, goto http://localhost/YourCIFolder/student
  2. You will see a display like the following,

    Input Form
  3. Try fill out the form with incorrect input (example, ID : AAA; Nama : (empty); Email : AAA)

    Wrong Input (example)
  4. Click Save. Then you will see the error is displayed as shown below,

    Validation Confirmation
  5. Now try to fill out the form with the correct input, as in the picture below, then Save. You will see a confirmation of success 😀 Also check your database, you should see the data you just entered in the tb_student 😀
    Correct Input (example)

    and this…

    Success Confirmation

p.s. Maybe there will be a question, this is a MVC, but, where is the model?

And the answer is : in CI, we are not always required to use models. Using code like $this->db->insert('tb_student', $data); is enough, according to complexity of your code..

Okay, (always) Happy Coding 😀

Kategori
PHP

Validasi Form dalam CodeIgniter

Studi Kasus : Membuat form beserta validasinya dengan CodeIgniter.

Kebutuhan Sistem : CodeIgniter PHP Framework, bisa didownload di sini. Dan Webserver Package.

Kebutuhan User : Kemampuan PHP, kemampuan Mysql, Kemampuan HTML, dan (sedikit saja cukuplah) kemampuan CodeIgniter.

Dalam men-develop sebuah aplikasi berbasis web, mau tidak mau pasti kita akan sering menggunakan form. Form sangat berguna untuk membuat antarmuka penginputan data ke dalam database. Untuk mem-prevent agar data input yang masuk ke database benar, atau sesuai dengan yang diinginkan, maka diperlukan suatu validasi. Pada bahasa pemrograman PHP, pada umumnya validasi dibuat dengan menggunakan fungsi ereg, dengan memanfaatkan regular expression (regex). Dan percayalah, kalau regex ini sangat rumit. Hahahah

Dengan menggunakan CodeIgniter, validasi jauh lebih mudah dibuat apabila dibandingkan dengan php biasa.

Ohya, ini adalah sebuah validasi server-side. Jelasnya, validasi dilakukan dari sisi server sehingga secara otomatis sistem validasi ini akan lebih aman dibandingkan dengan client-side validation (biasanya dibuat dengan javascript)

Okay, langsung praktikum…

Step 1 : Konfigurasi CI

  1. Buka file config.php yang berada dalam folder system-application-config-config.php
  2. Ubah base url, sesuaikan dengan lokasi dimana folder CI-mu berada (tempat ekstrak-an tadi). Contoh : Folder CI anda berada dalam folder www/ci

    maka ubah baris $config['base_url']="http://example.com/";
    dengan
    $config['base_url'] = "http://localhost/ci/";

  3. Setting database. Buka file database.php yang berada dalam folder yang sama dengan config.php. Ubah hostname, username, password, dan nama database. Sesuaikan dengan pengaturan mysql anda. Contoh :

    $db['default']['hostname'] = "localhost";
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "db_code";

Step 2 : Siapkan database

  1. Buat database dengan nama db_code (via phpmyadmin)
  2. Siapkan tabel dengan nama tb_student (untuk strukturnya, lihat gambar dibawah ini)
    tb_student's structure
  3. Ok, we’re done with database !

Step 3 : Membuat Controller

  1. Ketikkan script dibawah ini dengan teks editor kesukaan anda,

    <?php
    class Student extends Controller {function Student(){
    parent::Controller();
    $this->load->library(array('table','validation'));
    $this->load->helper('url');
    }
    function index() {
    $this->_set_fields();
    $data['title'] = 'Add New Student';
    $data['message'] = '';
    $data['action'] = site_url('student/addStudent');
    $this->load->view('addStudent_view', $data);
    }
    function addStudent(){
    $data1['title'] = 'Add New Student';
    $data1['action'] = site_url('student/addStudent');
    $this->_set_fields();
    $this->_set_rules();
    // menjalankan validasi
    if ($this->validation->run() == FALSE){
    $data['message'] = '';
    }else{
    // menyimpan data
    $data= array('id' => $this->input->post('id'),
    'nama' => $this->input->post('nama'),
    'email' => $this->input->post('email')
    );
    $this->db->insert('tb_student', $data);
    $data1['message'] = 'Sukses';
    }
    // load view
    $this->load->view('addStudent_view', $data1);
    }
    function _set_fields(){
    $fields['id'] = 'id';
    $fields['nama'] = 'nama';
    $fields['email'] = 'email';
    $this->validation->set_fields($fields);
    }
    // berikut adalah rule-rule untuk validasi
    function _set_rules(){
    $rules['id'] = 'trim|required|numeric';
    $rules['nama'] = 'trim|required';
    $rules['email'] = 'trim|required|valid_email';
    $this->validation->set_rules($rules);
    $this->validation->set_message('required', '* harus diisi');
    $this->validation->set_message('numeric', '* hanya boleh diisi dengan angka');
    $this->validation->set_message('valid_email', '* email tidak valid');
    $this->validation->set_error_delimiters('<p>', '</p>');
    }
    }
    ?>

  2. Simpan dalam folder system-application-controllers, dengan nama student.php

Step 4 : Membuat View

  1. Ketikkan script dibawah ini,

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Form Validation CI</title>
    </head>
    <body>
    <h1><?php echo $title; ?></h1>
    <?php if (isset($message)) echo $message; ?>
    <form method="post" action="<?php echo $action; ?>">
    <table>
    <tr>
    <td valign="top">ID*</td>
    <td><input type="text" name="id" value="<?php echo $this->validation->id; ?>"/>
    <span style="color:red;"> <?php echo $this->validation->id_error; ?></span></td>
    </tr>
    <tr>
    <td valign="top">Nama<span style="color:red;">*</span></td>
    <td><input type="text" name="nama" value="<?php echo $this->validation->nama; ?>"/>
    <span style="color:red;"> <?php echo $this->validation->nama_error; ?></span></td>
    </tr>
    <tr>
    <td valign="top">Email<span style="color:red;">*</span></td>
    <td><input type="text" name="email" value="<?php echo $this->validation->email; ?>"/>
    <span style="color:red;"> <?php echo $this->validation->email_error; ?></span></td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td><input type="submit" value="Save"/></td>
    </tr>
    </table>
    </form>
    </body>
    </html>

  2. Simpan dalam folder system-application-views, dengan nama addStudent_view.php

Step 5 : Testing Code

  1. Buka browser, pergi ke http://localhost/namaFolderCIKamu/student
  2. Anda akan melihat tampilan seperti berikut,
    Input Form
  3. Coba isi form dengan input salah (contoh, ID : AAA; Nama : (kosongi saja); Email : AAA)
    Wrong Input (example)
  4. Pilih Save. Maka anda akan melihat eror ditampilkan seperti gambar dibawah,
    Validation Confirmation
  5. Sekarang coba dengan isian benar, seperti pada gambar dibawah, lalu Save. Anda akan melihat konfirmasi sukses 😀 Cek juga database anda, seharusnya anda akan melihat data yang baru saja anda masukkan di dalam tb_student 😀
    Correct Input (example)
    Success Confirmation

p.s. Mungkin akan ada yang tanya, ini coding CI yang katanya MVC kok gak pakai model?

Jawabannya adalah : dalam CI, kita tidak selalu diharuskan memakai model. Menggunakan code seperti $this->db->insert('tb_student', $data); adalah sudah cukup, sesuai dengan tingkat kerumitan code anda.

Okay, (always) Happy Coding 😀