Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select box validation in Codeigniter

i am new to Codeigniter and I have some trouble in select box validation. I want default select value at beginning.

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

how can i make it required field in form and display error message on select of zero "0" value.

like image 833
S.Sid Avatar asked Nov 30 '22 03:11

S.Sid


2 Answers

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;
}
like image 88
Damien Pirsy Avatar answered Dec 04 '22 10:12

Damien Pirsy


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');
like image 39
xamiax Avatar answered Dec 04 '22 08:12

xamiax