问题
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.
回答1:
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;
}
回答2:
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');
回答3:
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;
}
}
来源:https://stackoverflow.com/questions/7721621/select-box-validation-in-codeigniter