Codeigniter:可以编辑表单并插入表单使用相同的验证吗?

时间:2016-04-20 04:34:49

标签: forms codeigniter validation

这是我对插入文章的函数验证。但是,当我使用编辑文章时,还有表单验证和相同的条件。所以我想只使用一个函数验证而不是复制和粘贴。

 function article_validation()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name','Article Name','required|trim|xss_clean');
        $this->form_validation->set_rules('content','Article body','required|trim|xss_clean');
        if($this->form_validation->run())
        {
            $this->load->model('article');
            $this->article->insert_article();
            redirect('article');

        }
        else
        {
            $this->load->view('page/insert');
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试在is_valid中创建controller方法,在controller中的任意位置调用,只需将您的is_valid功能设为私有,以避免被路由。

Class Articles {
       private function is_valid(){
            $this->load->library('form_validation');
            $this->form_validation->set_rules('name','Article Name','required|trim|xss_clean');
            $this->form_validation->set_rules('content','Article body','required|trim|xss_clean');

            return $this->form_validation->run();
       }

       public function create_article()
       {
           if($this->is_valid()){
                //save in DB
           }
       }

       public function edit_article($id)
       {
           if($this->is_valid()){
                //save in DB
           }
       }
}