Home > Software design >  Unable to validate form in codeigniter. After submitting form serverside validation is not happening
Unable to validate form in codeigniter. After submitting form serverside validation is not happening

Time:12-27

After submitting the view page, if the form fields don't contain values then error messages should appear, but in my case, null values are inserted in the database. So please help me where I am going wrong.

If form fields are empty then, if condition should be executed and then view page should be shown with error messages, instead of executing if condition its executing other code and inserting null values in data base. Controller

public function test_submit()
{
    
        $this->load->library('form_validation');
        $this->form_validation->set_rules('test_name', 'Test Name', 'trim|required|is_unique[add_test.TestName]');
        $this->form_validation->set_rules('description', 'Description', 'trim|required');
        $this->form_validation->set_rules('test_price', 'Test Price', 'trim|required');
        $this->form_validation->set_rules('correct_answer', 'Corrent Answer', 'trim|required');
        $this->form_validation->set_rules('wrong_answer', 'Wrong Answer', 'trim|required');
        
     if ($this->form_validation->run() == FALSE) 
     {

        $this->load->view('add_test_view');

     }
        
    $test_name=$this->input->post('test_name');
    $description=$this->input->post('description');
    $test_price=$this->input->post('test_price');
    $correct_answer=$this->input->post('correct_answer');
    $wrong_answer=$this->input->post('wrong_answer');
    
        
    $insert_data = array(
        'TestName' =>$test_name,
        'Description' => $description,
        'Price' => $test_price,
        'CorrectAnswerMarks' => $correct_answer,
        'WrongAnswerDeduction' => $wrong_answer
        
            
    );
        
    $result=$this->test_model->add_test($insert_data);
    
    $this->session->set_tempdata('success', "Test with name ".$test_name." Is Added Successfully.","20");
    redirect('testmodule/addtest', 'refresh');  
    
     }

CodePudding user response:

You should insert the data in else part of the validation like below:

if ($this->form_validation->run() == FALSE) 
{
 $this->load->view('add_test_view');
} else {
 // Insert code should go here
}

This will ensure data insertion only when validation is succefull. You should make use of the validation_error() function to display the error message like below:

if ($this->form_validation->run() == FALSE){
 $this->session->set_flashdata("error", validation_errors());
 redirect('your_controller/your_function');
}

In the above all the errors due to which validtion failed will be displayed on the view. Using redirect also ensures the execution of that function stops there . You have to use below in you view:

<div ><b><?=$this->session->flashdata('error');?></b></div>
  • Related