【问题标题】:Validate POST array parameters in codeigniter using form validation library使用表单验证库在 codeigniter 中验证 POST 数组参数
【发布时间】:2016-11-24 05:59:09
【问题描述】:

在 AJAX 请求中,我们如何验证接收到的 POST 数组?我正在使用 CodeIgniter 框架的 form_validation 库进行验证。 我能够毫无问题地验证字符串、整数和数值。但是当涉及到整数数组时,它就无济于事了。

以下是我的代码:

$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'实际上是一个通过ajax请求发布的数组。我用来验证的回调函数如下:

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;
        }
    }

在回调函数中,我想我得到的不是'product_categoryid_array'作为一个数组,而是实际上是一个字符串。

在某些情况下,我收到错误“未初始化的字符串偏移量”。如何成功验证帖子数组。

【问题讨论】:

    标签: ajax codeigniter validation


    【解决方案1】:

    如果以下关于$array 的所有条件都为真,validate_product_info 将返回 TRUE

    1. $array 是一个数组
    2. 不为空
    3. $array 中的所有值都是数字(或数字字符串)
    4. 所有数值都大于 0

    否则此函数返回FALSE;

    这就是我理解您的代码的方式。希望这就是你想要的。

    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;
    }
    

    【讨论】:

    • 我会试试这个。
    猜你喜欢
    • 2016-12-14
    • 2011-09-01
    • 1970-01-01
    • 2013-04-29
    • 2014-10-17
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多