无法在 codeigniter 中验证表单。提交表单后,如果表单为空,则不会发生服务器端验证,空值正在插入数据库

Unable to validate form in codeigniter. After submitting form serverside validation is not happening if form is empty null values are inserting db

提交视图页面后,如果表单字段不包含值,则应该会出现错误消息,但在我的例子中,数据库中插入了空值。所以请帮助我哪里出错了。

如果表单字段为空,则应执行 if 条件,然后应显示带有错误消息的视图页面,而不是执行 if 条件,而是执行其他代码并在数据库中插入空值。 控制器

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');  
    
     }

您应该将数据插入验证的其他部分,如下所示:

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

这将确保仅在验证成功时插入数据。 您应该使用 validation_error() 函数来显示如下错误消息:

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

在上面所有由于验证失败而导致的错误都将显示在视图上。使用重定向还可以确保该函数的执行停在那里。您必须在视图中使用以下内容:

<div class="text-danger text-center text-bold"><b><?=$this->session->flashdata('error');?></b></div>