user1610549 user1610549 - 1 month ago 15
PHP Question

CodeIgniter form validation not working properly

I have a form set up in a controller that both loads the form and its previously populated contents from a database and processes the form as needed. The problem is $this->form_validation->run() never evaluates to FALSE, even if rules are not met.

Controller:

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


Model:

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


View:

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


Thanks in advance.

Answer Source

syntax for setting rule is

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

by considering rules your set rule line will be

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