在Codeigniter中选择框验证

时间:2011-10-11 05:09:41

标签: php codeigniter codeigniter-form-helper

我是Codeigniter的新手,我在选择框验证方面遇到了一些麻烦。我想要开始时的默认选择值。

<select name="schooGroups[]">
<option value="0">Select User Group</option>
<option value="1">Admin</option>
</select>

如何在表单中创建必填字段并在选择零“0”值时显示错误消息。

3 个答案:

答案 0 :(得分:18)

默认情况下,此选项将标记为“已选择”。你想要一个多选下拉菜单,对吗?

<select name="schoolGroups[]" multiple="multiple">
<option value="0" selected="selected">Select User Group</option>
<option value="1">Admin</option>
</select>

至于验证,您可能想要构建自己的验证规则:

你的控制器的方法:

//...
$this->form_validation->set_rules('schoolGroups','School groups','required|callback_check_default');
$this->form_validation->set_message('check_default', 'You need to select something other than the default');

//...

添加其他方法:

function check_default($array)
{
  foreach($array as $element)
  {
    if($element == '0')
    { 
      return FALSE;
    }
  }
 return TRUE;
}

如果您只想要一个选择(无法多选),那就更容易了:

HTML:

<select name="schoolGroups">
<option value="0" selected="selected">Select User Group</option>
<option value="1">Admin</option>
</select>

验证方法:

 $this->form_validation->set_rules('schoolGroups','School groups','required|callback_check_default');
  $this->form_validation->set_message('check_default', 'You need to select something other than the default');

回调:

function check_default($post_string)
{
  return $post_string == '0' ? FALSE : TRUE;
}

答案 1 :(得分:2)

正确的方法是将默认选项的值设置为空!然后,您可以使用简单的form_validation规则,例如文本字段:

<select name="schoolGroups">
  <option value="">Select User Group</option>
  <option value="1">Admin</option>
</select>

$this->form_validation->set_rules('schoolGroups','School groups','required');

答案 2 :(得分:1)

这个对我有用。

观点

<select name="schoolGroups[]" multiple="multiple">
    <option value="">Select User Group</option>
    <option value="1">Admin</option>
</select>

控制器

$this->form_validation->set_rules('schoolGroups','School groups','callback_check_default');

<强> CALLBACK

function select_validate()
{
    $choice = $this->input->post("schoolGroups");
    if(is_null($choice))
    {
        $choice = array();
    }
    $schoolGroups = implode(',', $choice);

    if($schoolGroups != '') {
        return true;
    } else {
        $this->form_validation->set_message('select_validate', 'You need to select a least one element');
        return false;
    }
}