0
votes

In AJAX requests, how can we validate POST arrays that are received? I am using form_validation library of the CodeIgniter framework for validation purposes. I am able to validate strings, integers and numeric values without problems. But when it comes to integer arrays, it doesn't help.

Following is my code:

$this->form_validation->set_rules('order_amount_paid', 'Amount Paid', 'trim|numeric');//This is ok and working

$this->form_validation->set_rules('product_categoryid_array[]', 'Product categories', 'trim|required|callback_validate_product_info');

'product_categoryid_array' is actually an array that is posted via ajax request. The callback function that I have used for validating this is as follows:

public function validate_product_info($array){
        if(count($array) <= 0){
            return FALSE;
        }
        elseif(count($array) > 0){
            $total_count = count($array);
            for($i = 0; $i < $total_count; $i++){
                if(($array[$i] != '' && !is_numeric($array[$i])) OR $array[$i] <= 0){
                    return FALSE;
                }
            }
            return TRUE;
        }
        else{
            return TRUE;
        }
    }

In the callback function, I think I am not getting 'product_categoryid_array' as an array, but in fact, as a string.

In some cases, I get an error 'Uninitialized string offset'. How can I validate post arrays successfully.

1

1 Answers

0
votes

validate_product_info will return TRUE if all of the following are true about $array

  1. $array is an array
  2. It is not empty
  3. All values in $array are a number (or a numeric string)
  4. All numeric values are greater than 0

Otherwise this function returns FALSE;

That is the way I understood your code. Hope that's what you wanted.

public function validate_product_info($array)
{
  if(empty($array) OR ! is_array($array))
  {
    return FALSE;
  }

  foreach($array as $key => $value)
  {
    if(empty($value) OR ! is_numeric($value) OR $value < 0)
    {
      return FALSE;
    }
  }
  return TRUE;
}