select box validation in Codeigniter

你。 提交于 2019-12-03 20:59:41

This will have the entry marked as "selected" as...selected by default. You want a multi-select dropdown, right?

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

As for validation, you might want to build your own validation rule:

Your controller's method:

//...
$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');

//...

The add this other method:

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

If you just want a single select (no ability to multiselect then) it's even easier:

html:

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

Method with validation:

 $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');

Callback:

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

The correct way of doing this is by setting the value of the default option to empty! Then you can use a simple form_validation rule like for a text field:

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

.

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

This one worked for me.

THE VIEW

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

THE CONTROLLER

$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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!