How To Make Form Validation Codeigniter?

179 views Asked by At

I want to make form validation on codeigniter

this is the code from alternatif.php on controller

class Alternatif extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->model("Alternatif_model");
        $this->load->model("User_model");
        if (!$this->session->userdata('email')) {
            redirect('auth');
        }
        $data['user'] = $this->db->get_where('users', ['email' => $this->session->userdata('email')])->row_array();
    }

public function tambahAlternatif()
    {
        $data['title'] = 'Tambah Alternatif';
        $data['user'] = $this->db->get_where('users', ['email' => $this->session->userdata('email')])->row_array();
        
        if ($this->input->post('nambahAlternatif')) {
            foreach ($this->input->post() as $key => $value) {
                if (strpos($key, "id_aspek_teknik-") !== false) {
                    $k = str_replace('id_aspek_teknik-', '', $key);
                    $this->Alternatif_model->tambahNilai($k);
                }
            }

            $this->Alternatif_model->tambahAlternatif();
            $this->session->set_flashdata('flash', 'ditambahkan');
            redirect('alternatif');

        } else {
 code
        }

    }

I want to ask where I can add the form validation on codeigniter?

1

There are 1 answers

0
Shaiful On

Add validation on Controller like:

        public function tambahAlternatif()
        {
                $this->load->helper(array('form', 'url'));

                $this->load->library('form_validation');

                if ($this->form_validation->run() == FALSE)
                {
                        // this block working when get error
                        $this->load->view('myform');
                }
                else
                { // when success
                        $this->load->view('formsuccess');
                }
        }

check official documentation here

Use this code on your view file (where your form was submitted) <?php echo validation_errors(); ?> it return your errors

Note: this validation errors on view file only work for PHP version <=7.3. PHP v8 not supported