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, $listTags, true) !== false) {
$validKey[] = $inputValue;
}
}
if (count($value) == count($validKey)) {
return true;
}
$error = "The {$field} is not valid.";
return false;
},
],