Displaying form error message when checkbox is not checked using CodeIgniter form validation library.
Currently, form error message is displayed only when checkbox is checked.
Here is AJAX call:
$('#add_user').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
method : "post",
data: $(this).serialize(),
dataType: "json",
success: function(result) {
if(result.success == true) {
alert('Success');
} else {
$.each(result.errors, function(key, value) {
var error = $('#' + key);
error.closest('div.form-group')
.find('.error').remove();
error.after(value);
});
}
}
});
});
And here is PHP controller:
$this->form_validation->set_rules('agreement', 'Agreement', 'callback_agreement_checkbox');
if($this->form_validation->run()) {
$data['success'] = true;
$this->load->view('Success');
} else {
foreach($this->input->post() as $key => $value) {
$data['errors'][$key] = form_error($key);
}
echo json_encode($data);
}
public function agreement_checkbox() {
if (empty($this->input->post('agreement'))) {
return FALSE;
} else {
$error = 'Please accept TOS';
$this->form_validation->set_message('agreement_checkbox', $error);
return TRUE;
}
}
When the form is submitted without checkbox checked, error message is not displayed (but it should). It's displayed only when checkbox is checked and it's wrong.
EDIT:
I've done some modifications for support of mixing different input data:
$this->form_validation->set_rules('first_name', 'First name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last name', 'trim|required');
$this->form_validation->set_rules('email', 'E-mail', 'trim|required');
$this->form_validation->set_rules('agreement', 'Agreement', 'required');
if($this->form_validation->run()) {
$data['success'] = true;
$this->load->view('Success');
} else {
foreach($this->input->post() as $key => $value) {
$data['errors'][$key] = form_error($key);
}
if (empty($this->input->post('agreement'))) {
$data['errors']['agreement'] = form_error('agreement', '<div id="agreement_error">', '</div>');
}
echo json_encode($data);
}