tags:

views:

266

answers:

1

I have a set of fields to validate. Here is the scenario.

Let's say I have fields shown below. Since the names are the same I put a number and add at the end.

job_title_1 company_name_1 responsibilities_1

job_title_2 company_name_2 responsibilities_2

job_title_3 company_name_3 responsibilities_3

In my view, I used (for statement) to loop and assign this number at the end of the field name, then pass the variable “ctr = 3” in my controller.

I use validation like this

  $validation_errors = array();
  for ($i = 1; $i <= $ctr; $i++)
  {
    $this->form_validation->set_rules('career_objectives_' . $i, 'Career objectives title', 'trim|required');                                                                                    
    $this->form_validation->set_rules('job_title_' . $i, 'Job title / position', 'trim|required');
    $this->form_validation->set_rules('company_name_' . $i, 'Company', 'trim|required');    
    $this->form_validation->set_rules('from_date_employment_' . $i, 'From date of employment', 'trim|required');            
    $this->form_validation->set_rules('to_date_employment_' . $i, 'To date of employment', 'trim|required');    
    $this->form_validation->set_rules('responsibilities_' . $i, 'Responsibilities type', 'trim|required');
    $this->form_validation->set_error_delimiters('<div class="valid-err">', '</div>');                    

    if ($this->form_validation->run() == FALSE)
    {
      $validation_errors[$i] = validation_errors();
    }                
  }

I decided to put the validation_errors in an array so that I could get this in my view and place the string error in a separate location. My problem now is even the job_title_1 only has error. All the job_title from 1 to 3 produced an error. I think validation_errors() was not clear to the next loop.

Any help would greatly appreciated.

I already posted it in CodeIgniter forums but I haven't got the right solutions.

+3  A: 

You don't want to run $this->form_validation->run() within your loop. It (correctly) runs three times, and since the validations don't clear when the form validation runs, it validates job_title_1 three times.

I take it you're trying to be specific to the user in which number employee/section the error occurs in. A better practice for this is to use the field-specific errors:

form_error('job_title_1');

Steven Xu