CodeIgniter 2.0 - validating arrays

10,758

An array must be passed to your set_rules call suffixed with opening / closing square brackets, like so:

$this->form_validation->set_rules('checkboxes[]', 'My Checkboxes', 'required');

There are more details in the CI user guide - https://www.codeigniter.com/user_guide/libraries/form_validation.html#using-arrays-as-field-names

To handle the check for your checkbox values to be one of several values, you would need to create a custom callback function - https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

Share:
10,758
RS7
Author by

RS7

Updated on August 27, 2022

Comments

  • RS7
    RS7 over 1 year

    I'm having some problems converting a piece of form validation code to CI 2.0. I'm trying to validate an array of checkboxes but for some reason validation fails to run the callback or doesn't validate.

    How can I validate an array of checkboxes so that at least one is checked and values must be one of the options (key of an options array)?

    EDIT:

    Here is a better explanation of where it is failing me. Lets say I has these fields:

    <input type="checkbox" value="1" name="purpose[]" />
    <input type="checkbox" value="2" name="purpose[]" />
    

    I've set two rules for purpose[] - one is the required rule, the other is a custom callback that checks that the value is present in a array of possible values.

    If I edit the name of the field to:

    <input type="checkbox" value="1" name="purpose[abc]" />
    

    or even change the value to "", the validation passes. It ignores the required rule and my custom callback.

    Anybody have an idea on how to deal with this?