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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With