CodeIgniter Forums
add new rule for multi_checkboxes - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Feature Requests (https://forum.codeigniter.com/forumdisplay.php?fid=29)
+--- Thread: add new rule for multi_checkboxes (/showthread.php?tid=88414)



add new rule for multi_checkboxes - datamweb - 09-05-2023

Multi-select checkboxes require a validation rule.

Currently, CI4 rules do not cover this issue.
Considering the common use of Multi-select checkboxes in websites, I suggest adding this rule to CI.

An example of implementation in the form of a closure that can be transferred to the rules class(CodeIgniter\Validation\Rules::class).

Code:
<label for="tags_multiple">Select Tags</label>
  <select name="tags[]" multiple id="tags_multiple">
  <option selected>Choose Tags</option>
  <?php foreach (service('settings')->get('App.tags') as $key => $value) : ?>
  <option value="<?= $key ?>"><?= $value ?></option>
  <?php endforeach; ?>
</select>

PHP Code:
            'tags' => [
                'required',
                static function ($value$data, &$error$field) {
                
                    
if (count($value) > 3) {
                        $error "You can only choose 3 {$field}.";
                        return false;
                    }

                    $listTags array_keys(service('settings')->get('App.tags'));
                    $validKey = [];
                    foreach ($value as $inputValue) {
                        if (array_search($inputValue$listTagstrue) !== false) {
                            $validKey[] = $inputValue;
                        }
                    }
                    if (count($value) == count($validKey)) {
                        return true;
                    }

                    $error "The {$field} is not valid.";

                    return false;
                },
            ], 



RE: add new rule for multi_checkboxes - kenjis - 09-05-2023

The current rules are all for string data. There is no rule for array data.
It would be better to add common rules for array.