Welcome Guest, Not a member yet? Register   Sign In
Form validation best practices
#1

[eluser]RobertSF[/eluser]
The CI guide on form validation shows the controller logic attempting to validate the form as the very first step, before even showing it. Like this --

Code:
function index()
{
if ($this->form_validation->run() == FALSE)
{
  $this->load->view('myform');
}
else
{
  $this->load->view('formsuccess');
}
}

But that doesn't distinguish between validation failing because the user hasn't entered any data and because the user entered data incorrectly. Would it be poor practice to test for form submission first?

Code:
function index()
if ($this->input->post('submit_button') == 'Ok'
{
  //User submitted the form, so validate it
  if ($this->form_validation->run())
  {
   //form is valid, so process it
   $this->load->view('formsuccess');
  }
  else
  {
   //form is not valid, so return error messages
   $data = validation_errors();
  }
}
else
{
  //First time displaying form
  $data = 'Please enter this data'; // or some other initial message
}
$this->load->view('myform', $data);

That is, more or less, how you code PHP when you're not using a framework, so I don't know if it's poor programming practice to do it this way when you are using a framework like CI. What do you think?
#2

[eluser]jairoh_[/eluser]
that's understandable. CI is just posting the basic usage of the validation library Big Grin
#3

[eluser]RobertSF[/eluser]
Ah, ok. Thanks a lot. :-)




Theme © iAndrew 2016 - Forum software by © MyBB