Here is my controller. All fields are required, and all are drop downs in the form. If all the fields are empty (no item selected in any drop down), the form just reloads with no error. If any one or two or three are selected, it correctly reports the unselected ones are in error because they are empty. It should report all are in error if none are selected, but it does not.
$baserules = 'trim|required';
$this->form_validation->set_rules('gender', 'Gender', $baserules . '|exact_length[1]');
$this->form_validation->set_rules('category', 'Category', $baserules . '|max_length[32]');
$this->form_validation->set_rules('state', 'State', $baserules . '|exact_length[2]');
$this->form_validation->set_rules('city', 'City', $baserules . '|max_length[32]');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('post/post', $data);
$this->load->view('templates/footer');
} else {
redirect('search');
}
I am using echo validation_errors(); in the view and it is showing the same thing. No errors when the form is empty, but correct errors if one, two, or three out of four are selected. Here is the view:
<form action="http://example.com/index.php/post/post" method="post" accept-charset="utf-8" class="form-horizontal" id="postForm" name="postForm" role="form">
<div class="form-group col-lg-12">
<div class="centered">
Please select each of the following and click continue.
</div>
<div class="column-quarter">
<select style="width:100%;" id="gender" name="gender" >
<option value="" selected disabled>select gender</option>
<option value="f">Female</option>
<option value="m">Male</option>
</select>
</div>
<div class="column-quarter">
<select style="width:100%;" id="category" name="category" >
<option value="" selected disabled>select category</option>
<option value="cat1">cat1</option>
<option value="cat2">cat2</option>
</select>
</div>
<div class="column-quarter">
<select style="width:100%;" id="state" name="state" >
<option value="" selected disabled>select state</option>
<option value="tx">TX</option>
<option value="tx">OH</option>
<option value="tx">MI</option>
</select>
</div>
<div id="citydiv" class="column-quarter">
<select style="color: #999; width:100%;" id="city" name="city">
<option value="" disabled>select city</option>
<option value="city1">city1</option>
<option value="city2">city2</option>
<option value="city3">city3</option>
</select>
</div>
</div>
<div class="form-group col-lg-12 centered">
<button type="submit" class="btn btn-success">Continue</button>
<button type="reset" class="btn btn-success">Clear</button>
</div>
</form>
Remove the disabled
attributes from your select
dropdowns.
For instance, the gender dropdown should be changed from
<option value="" selected disabled>select gender</option>
to
<option value="" selected>select gender</option>
By defaulting them to disabled, they will not be submitted when you submit the form. See the tip section on W3Schools.