Codeigniter 3:将 "field is required" 替换为 "field can not be empty"

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

我正在 Codeigniter 3.1.8 中开发一个基本的博客应用程序

我有一个 create post 表单和一个 update post 表单。他们都有验证规则。对于更新表单的无效字段 "warnings",我想用 "field can not be empty".

替换表达式 "field is required"

这是代码(帖子控制器):

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

如果标题字段为空,我希望警告为:"The Title field can not be empty."

我应该add/change更新什么方法?

你可以这样做:

在您的更新方法中设置所需的消息,如下所示:

$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*/

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

我已经通过这种方式获得了所需的无效字段警告:

public function update() {
    // Form data validation rules
    $this->form_validation->set_rules('title', 'Title', 'required',  array('required' => 'The %s field can not be empty'));
    $this->form_validation->set_rules('desc', 'Short description', 'required',  array('required' => 'The %s field can not be empty'));
    $this->form_validation->set_rules('body', 'Body', 'required',  array('required' => 'The %s field can not be empty'));
    $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);
    }
}