【问题标题】:Codeigniter form validation required arrayCodeigniter 表单验证所需的数组
【发布时间】:2016-05-19 14:49:42
【问题描述】:

我有一个带有数组字段的表单,允许用户选择多个类别 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 数组,表单验证在所需的检查中也失败了,并且说我必须提交一些,即使我已经提交了。

【问题讨论】:

    标签: php codeigniter codeigniter-3


    【解决方案1】:

    来自 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[]');
    

    【讨论】:

    • 我已经这样做了,但是如果我在没有选择任何类别的情况下提交表单,验证应该会失败,但它不会
    • Ohkk 然后检查你的 html,如果它的第一个选项不应该有任何值,例如 标记值中没有空格 :)
    • @geoffs3310 你也可以试试 $this->form_validation->set_rules('event_categories[]', 'Categories', 'trim|required');
    • 啊我已经整理好了,因为我用的是form_error('event_categories')而不是form_error('event_categories[]')
    • 编辑为您建议的答案:)
    【解决方案2】:

    现在解决了,因为我打电话给form_error('event_categories')而不是form_error('event_categories[]')

    所以只是为了澄清你是否提交了一个需要正确验证规则格式的数组:

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

    【讨论】:

      猜你喜欢
      • 2016-12-14
      • 2011-08-13
      • 1970-01-01
      • 2015-10-12
      • 2016-09-06
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 2017-02-06
      相关资源
      最近更新 更多