How would I write in CodeIgniter, if option equals "Select" Throw an error saying that selecting an option is required?
<option>Select</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
Many thanks in advance.
<select id='my_options'>
<option value=0>Select</option>
<option value=1>Option 1</option>
<option value=2>Option 2</option>
<option value=3>Option 3</option>
<option value=4>Option 4</option>
</select>
in your controller you can do:
$this->form_validation->set_rules('my_options','Select Options','required|greater_than[0]');
obviously this assumes that you are using the form_validation class and your form is directed to a controller where you would write the above line of code ..will that do ?
As far as I know , the only way to work with such a case is creating a custom function. It's not that hard to work with it, for example:
First of all , create the rule for form_validation library:
$this->form_validation->
set_rules('my_dropdown', 'Dropdown', 'callback_my_func');
Where my_func
is the validation function which returns either true or false(and error message as well).
And here's an example for my_func
:
Note: You must specify the value of each option so you can work with them.
In my example, you'll set the "Select" option to 0. By doing the following:
<option value="0">Select</option>
...And here's the function:
function my_func($dropdown_selection){
//If the selection equals "Select" that means it equals 0(which is the "hidden" value of it)
if($dropdown_selection === 0) {
//Set the message here.
$this->form_validation->set_message('my_func', 'You must specifiy a value for your dropdown');
//Return false, so the library knows that something is wrong.
return FALSE;
}
//If everything is OK, return TRUE, to tell the library that we're good.
return TRUE:
}
This code should work, but it's not tested. You can always go creative and add more code and tailor it to your specific web app. For more information, check CI's documentation about form_validation library here.