Welcome Guest, Not a member yet? Register   Sign In
add new rule for multi_checkboxes
#1

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;
                },
            ], 
Reply
#2

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB