Form validation should include not only checking whether the field is filled out or not. For this reason, you should use Ajax to send the appropriate data to the server and use server-side validation.
At the top of the page, add a hidden div to display validation errors:
<div class="alert alert-danger col-xs-12 hidden" id="error"></div>
Add a generic "validate" class to all buttons that will trigger validation of your form. We will have three different sets of validation logic. Give the field an identifier that matches the function name (for example, "validate_1", "validate_2", etc.).
<a class="btn btn-primary btnNext pull-right validate" id="validate_1">Next</a> <a class="btn btn-primary btnNext pull-right validate" id="validate_2">Next</a>
Update your jQuery to enable the AJAX POST function. This function sends data to a server, where you can use Codeigniter's own form validation:
$('.btnPrevious').click(function() { $('.nav-pills > .active').prev('li').find('a').trigger('click'); }); $(document).on('click','.validate',function(e){ e.preventDefault(); if($('#error').is(":visible")){ $('#error').empty().addClass('hidden'); //refresh error message if it was triggered previously } var form = $(this).closest('form'); $.ajax({ url: this.id, type: 'POST', data: form.serialize(), dataType: 'html', success: function(data) { var result = $.parseJSON(data); if(result["error"]===undefined){ $('.nav-pills > .active').next('li').find('a').trigger('click'); }else{ $('#error').append(result["error"]).removeClass('hidden'); } }, error: function() { } }); });
And then in your controller:
function validate_1(){ //function name matches element id $this->load->library('form_validation'); $this->form_validation->set_rules('admission_no', 'Admission Number', 'required|integer|greater_than[0]'); $this->form_validation->set_rules('application_no', 'Application Number', 'required|integer|greater_than[0]'); $this->form_validation->set_rules('academic_year', 'Academic Year', 'required|integer|greater_than[0]'); if($this->form_validation->run() == TRUE){ echo json_encode(array('success' => 1)); }else{ echo json_encode(array('error' => validation_errors())); } } function validate_2(){ $this->load->library('form_validation'); $this->form_validation->set_rules('firstname', 'First Name', 'required'); $this->form_validation->set_rules('dob', 'Date of Birth', 'required'); $this->form_validation->set_rules('student_address', 'Address', 'required'); if($this->form_validation->run() == TRUE){ echo json_encode(array('success' => 1)); }else{ echo json_encode(array('error' => validation_errors())); } }
This will allow you to verify that the data has been sent and that it is valid. The user will still be able to click on their own to switch from one navigation pill to another, but they will not be able to submit the form without filling in the required fields.
