Search code examples
codeignitervalidationvalidationrules

Codeigniter 3: replace "field is required" with "field can not be empty"


I am working on a basic blog application in Codeigniter 3.1.8.

I have a create post form and an update post form. They both have validation rules. For the update form's invalid field "warnings", I want to replace the expression "field is required" with "field can not be empty".

Here is the code (Posts controller):

public function edit($id) {
    $data = $this->Static_model->get_static_data();
    $data['post'] = $this->Posts_model->get_post($id);
    $data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
    $this->load->view('partials/header', $data);
    $this->load->view('edit');
    $this->load->view('partials/footer');
}

public function update() {
    // Form data validation rules
    $this->form_validation->set_rules('title', 'Title', 'required');
    $this->form_validation->set_rules('desc', 'Short description', 'required');
    $this->form_validation->set_rules('body', 'Body', 'required');
    $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

    $id = $this->input->post('id');
    if ($this->form_validation->run()) {
        $this->Posts_model->update_post($id, $data);
        redirect('posts/post/' . $id);
    } else {
        $this->edit($id);
    }
}

If the title field is empty I want the warning to be: "The Title field can not be empty."

What shall I add/change to the update method?


Solution

  • You can do like this :

    in your update method set message for required like this :

    $this->form_validation->set_rules('title', 'Title', 'required',
                            array('required' => 'The Title field can not be empty')
                    );
    $this->form_validation->set_rules('desc', 'Short description', 'required',
                            array('required' => 'Short description can not be empty')
                   );
    
    /* use same for other fields*/
    

    for more : https://www.codeigniter.com/user_guide/libraries/form_validation.html#setting-validation-rules