Form validation rule to validate checkbox in Codeigniter

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.

Form Validation in Controller:

To validate the checkbox define a function in your controller class as given below:

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.

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.

Like this Post? Share