geo*_*310 2 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]');
Run Code Online (Sandbox Code Playgroud)
我扩展了表单验证库并添加了现成的现存方法,如下所示:
/**
* 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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,即使我提交了有效的类别ID数组,表单验证也未能通过所需的检查,并说即使我已经提交,也必须提交一些。
小智 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');
Run Code Online (Sandbox Code Playgroud)
应该
$this->form_validation->set_rules('event_categories[]', 'Categories', 'required');
Run Code Online (Sandbox Code Playgroud)
显示表格错误使用
echo form_error('event_categories[]');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6295 次 |
最近记录: |