CodeIgniter表单验证无法正常工作

时间:2012-11-30 14:39:57

标签: php codeigniter validation

我在控制器中设置了一个表单,它既可以从数据库加载表单及其先前填充的内容,也可以根据需要处理表单。问题是$ this-> form_validation-> run()永远不会评估为FALSE,即使规则不符合。

控制器:

public function edit_version($node, $lang)
{
    // load form validation class
    $this->load->library('form_validation');

    // set validation rules
    $this->form_validation->set_rules("title|Title|required");

    // run validation
    if ($this->form_validation->run() !== FALSE)
    {
        // save input to database
        die("validation successful");
    }
    else
    {
        // either validation was not passed or no data to validate
        // load page edition view and display databse contents

        // load page model
        $this->load->model("page_model");

        // get the page from database
        $data["page"] = $this->page_model->get_page($node, $lang);

        // load views
        $this->load->view("admin/header.php", array("title" => "Edit page no.: $node, $lang version - Admin"));
        $this->load->view("admin/pages/edit_page.php", $data);
        $this->load->view("admin/footer.php");
    }
}

型号:

class Page_model extends CI_Model
{
public function get_page($node, $lang)
{
    // load the page
    return $this->db->get_where("pages", array("node" => $node, "lang" => $lang))->row();
}

public function save_version($page)
{
    $this->db->where("node", $page["node"]);
    $this->db->where("lang", $page["lang"]);
    $this->db->update("pages", $page);
}

public function search($query)
{
    return $this->db->get_where("pages", $query)->result();
}
}

查看:

<h2>Edit page</h2>
<?php
// load form helper
    $this->load->helper("form");

// open a form
echo form_open("admin/page/{$page->node}/edit/{$page->lang}");

// print validation errors
echo validation_errors();

// title and content fields
echo form_label("Title: ", "title");
echo form_input("title", set_value("title", $page->title));

// aesthetic line break
echo "<br>";

echo form_label("Content: ", "content") . "<br>";
echo form_textarea("content", set_value("content", $page->content));

// save button and close form
echo form_submit("submit", "Save page");
echo form_close();

提前致谢。

3 个答案:

答案 0 :(得分:4)

设置规则的语法为

 $this->form_validation->set_rules('field_name', 'Label', 'rule1|rule2|rule3');

通过考虑规则,您的设置规则行将

$this->form_validation->set_rules('title','Title', 'required");

答案 1 :(得分:2)

我不是CodeIgniter经验丰富的开发者,但是从文档中获取正确的语法不是以下内容?

$this->form_validation->set_rules("title","Title","required");

根据此链接: http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules

答案 2 :(得分:0)

使用

$this->form_validation->set_rules("title","Title","required");

而不是

$this->form_validation->set_rules('title','Title','required');

我测试了这个。它就像一个魅力。