Checkbox validation in Codeigniter form is not as straight as validating other input types. As usually we need to check if a checkbox is checked or unchecked during form submission likewise if user accepted or not ‘TOS (Terms of Services)’ through checkbox. So I have provided a form validation rule to validate checkbox as ‘required‘ rule can’t do the task.
In PHP we use ‘isset()‘ to check if a checkbox is checked or not. Here we are doing the same with help of callback to implement our own validation method which is supported by Codeigniter Validation System. And we are also specifying our own error message.
Form validation rule to validate checkbox in Codeigniter
The Form: Assume that we have a checkbox field with name ‘accept_terms_checkbox‘ in our form.
1 2 3 4 5 6 7 8 | <form> ... <input type="checkbox" name="accept_terms_checkbox" value="Accept TOS" /> Accept Terms of Services<br> <?php echo form_error('accept_terms_checkbox') ?> </form> |
Form Validation in Controller:
To validate the checkbox define a function in your controller class as given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function accept_terms() { //if (isset($_POST['accept_terms_checkbox'])) if ($this->input->post('accept_terms_checkbox')) { return TRUE; } else { $error = 'Please read and accept our terms and conditions.'; $this->form_validation->set_message('accept_terms', $error); return FALSE; } } |
This function above is a callback function which is called at the time of validation by controller method which is handling the form. Now place the rule among other validation rule for the form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php $this->form_validation->set_rules('password','Password','trim|required|xss_clean'); ... ... $this->form_validation->set_rules('accept_terms_checkbox', '', 'callback_accept_terms'); ... if ($this->form_validation->run()) { // Do this } else { // Do that } ?> |
In this way you can validate checkbox field or any other input field. Just place a callback_FUNCTION_NAME
as third parameter while setting rules, define the function as function FUNCTION_NAME()
and define error message by passing the function name itself as first parameter to ‘set_message()‘ within it.
That’s all needed to implement form validation rule to validate checkbox or to apply custom validation in Codeigniter. Also read: retain status of checkbox during form submits.