how to validate array value in codeigniter

后端 未结 2 1558
心在旅途
心在旅途 2020-12-03 12:21

I have in my form work experience which is added dynamically with input as organisation name, department name, position and duration.


    

        
相关标签:
2条回答
  • 2020-12-03 12:30

    So as suggested by @ Hashem Qolami I did the following changes in my code and it worked.

    $organization    = $this->input->post('organization');
    $department      = $this->input->post('department');
    $positions       = $this->input->post('positions');
    $duration        = $this->input->post('duration');
    
    foreach($organization as $ind=>$val) 
    {
        $org  = $organization[$ind];
        $dept = $department[$ind];
        $pos  = $positions[$ind];
        $dura = $duration[$ind];
    
        $this->form_validation->set_rules("organization[".$ind."]", "Organization", "trim|xss_clean|max_length[1]");
        $this->form_validation->set_rules("department[".$ind."]", "Department", "trim|xss_clean|max_length[50]");
        $this->form_validation->set_rules("positions[".$ind."]", "Position", "trim|xss_clean|max_length[40]");
        if(!empty($dura))
           $this->form_validation->set_rules("duration[".$ind."]", "Duration", "trim|xss_clean|integer");
    }
    

    and displayed my errors as follows

     for($i = 0; $i < count($organization); $i++) {
         echo form_error("organization[".$i."]"); 
         echo form_error("department[".$i."]"); 
         echo form_error("positions[".$i."]"); 
         echo form_error("duration[".$i."]");
      }
    
    0 讨论(0)
  • 2020-12-03 12:45

    It doesn't let me submit the form If so, It sounds like a bug.

    Temporarily, you can check whether duration[] array is empty or not:

    if (! empty($_POST['duration'])) {
        $this->form_validation->set_rules('duration[]',"Duration", "trim|xss_clean|numeric");
    }
    

    I'll update my answer if I found the main solution.


    Update: This is a bug as I expected, I opened a PR at CodeIgniter Repository, that would fix this issue.

    0 讨论(0)
提交回复
热议问题