Welcome Guest, Not a member yet? Register   Sign In
Should form_validation only be done if post() is true?
#1

[eluser]Scared[/eluser]
In the CI news tutorial the controller for creating a news item sets up the validation rules and tests to see if they succeed. If they do, it saves the news item and loads the success view, otherwise it reloads the form view and displays the appropriate error messages.

I see a lot of examples like this where the form validation rules are setup and tested near the top of the controller. My question is, shouldn't these rules be setup and tested only if $this->input->post() is true?

To me it seems like overhead creating the validation rules and running them when the form might not have even been submitted yet.

Here's the example taken from the tutorial

Code:
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');

$data['title'] = 'Create a news item';

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

if ($this->form_validation->run() === FALSE)
{
  $this->load->view('templates/header', $data);
  $this->load->view('news/create');
  $this->load->view('templates/footer');

}
else
{
  $this->news_model->set_news();
  $this->load->view('news/success');
}
}

Here's my modified example which I think is more efficient:

Code:
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');

$data['title'] = 'Create a news item';

if ($this->input->post())
{

  /* Save validation requirements for if the form was submitted, rather than just displayed */
  $this->form_validation->set_rules('title', 'Title', 'required');
  $this->form_validation->set_rules('text', 'text', 'required');

  if ($this->form_validation->run() === TRUE)
  {
   $this->news_model->set_news();
   $this->load->view('news/success');
   exit;
  }
}

$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}

Am I over-thinking this?

Thanks


Messages In This Thread
Should form_validation only be done if post() is true? - by El Forum - 01-20-2014, 06:15 AM
Should form_validation only be done if post() is true? - by El Forum - 01-20-2014, 11:15 AM



Theme © iAndrew 2016 - Forum software by © MyBB