Codeigniter表单验证需要数组

时间:2016-02-09 14:53:19

标签: php codeigniter codeigniter-3

我有一个带有数组字段的表单,允许用户选择多个类别ID。他们必须至少选择一个类别,但可以选择多个类别。我的表单验证需要确保至少指定了一个类别ID,然后对于每个类别ID,它需要检查它是否是有效类别。这就是我所拥有的:

$this->form_validation->set_rules('event_categories', 'Categories', 'required');
$this->form_validation->set_rules('event_categories[]', 'Categories', 'integer|exists[category.id]');

我扩展了表单验证库并添加了如下所示的exists方法:

/**
 * Checks to see if a value exists in database table field
 *
 * @access  public
 * @param   string
 * @param   field
 * @return  bool
 */
public function exists($str, $field)
{
    //die("fe");
    list($table, $field)=explode('.', $field);
    $query = $this->CI->db->limit(1)->get_where($table, array($field => $str));

    if($query->num_rows() !== 0) {
        return TRUE;
    }
    else {
        if(!array_key_exists('exists',$this->_error_messages)) {
            $this->CI->form_validation->set_message('exists', "The %s value does not exist");
        }
        return FALSE;
    }
}

问题是即使我提交了一个有效的类别ID数组,表单验证在所需的检查上失败,并说我必须提交一些,即使我有。

2 个答案:

答案 0 :(得分:5)

来自CI DOCS https://www.codeigniter.com/user_guide/libraries/form_validation.html#using-arrays-as-field-names

$this->form_validation->set_rules('event_categories', 'Categories', 'required');

应该是

$this->form_validation->set_rules('event_categories[]', 'Categories', 'required');

显示表单错误使用

echo form_error('event_categories[]');

答案 1 :(得分:0)

现在解决了这个问题,原因是我打电话给form_error('event_categories')而不是form_error('event_categories[]')

因此,只是为了澄清您是否提交了一个需要正确的验证规则格式的数组:

$this->form_validation->set_rules('event_categories[]', 'Categories', 'required');