Validate the quantity of items in an array (CheckboxList) sent by the form

I have a voting form and I would like to validate the minimum and maximum number of candidates that each voter can vote for. These max and min values are stored in the logged user’s session.

That is, I need to validate the number of items (checkbox selected) that the form sent.

MODEL Voto.php

public static function tableName()
    {
        return 'voto';
    }

    public function rules()
    {
        return [
            [['eleicao_id', 'candidato_id', 'cargo_id', 'urna_id', 'created'], 'required','message'=> 'Selecione no mínimo 1 candidato!'],
            [['eleicao_id', 'cargo_id', 'urna_id'], 'integer'],
            [['created','candidato_id'], 'safe'],
            [['eleitor_hash'], 'string', 'max' => 255],
        ];
    }

FORM _form_votacao.php

<?php $form = ActiveForm::begin(); ?>
    <div class="row">
    <?php
    $candidato = ArrayHelper::map(candidato::find()
                    ->where(['status' => 1])
                    ->Andwhere(['eleicao_id' => Yii::$app->user->identity->eleicao_id])
                    ->orderBy("nome ASC")
                    ->all(), 'id', 'nome'
                );

    echo $form->field($model, 'candidato_id')->checkboxList($candidato, [
        'class'         => 'h4',
        'data-toggle'   => 'button',
        'item'          => function($index, $label, $name, $checked, $value) {
            return "<label class='col-md-5'><input type='checkbox' {$checked} name='{$name}' value='{$value}'> {$label}</label>";
        }])->label(false);
    ?>
    </div>
    <br>
    <div class="row text-center">
        <div class="form-group">
            <?= Html::submitButton('Confirmar', ['class' => 'btn btn-success']) ?>
        </div>
    </div>

    <?php ActiveForm::end(); ?>

CONTROLLER VotoController.php

public function actionVotacao()
    {
        $model      = new Voto();
        $hash       = Yii::$app->security->generateRandomString(20);
        $eleicao_id = Yii::$app->user->identity->eleicao_id;
        $eleicao    = Eleicao::find()->where(['id' =>$eleicao_id])->one();
        $min_voto   = $eleicao->flag_min_votos;
        $max_voto   = $eleicao->flag_max_votos;

        if ($model->load(Yii::$app->request->post())) {
           
           foreach ($model->candidato_id as $candidato_id) {
                $model = new voto();
                $model->candidato_id    = $candidato_id;
                $model->eleitor_hash    = $hash;
                $model->eleicao_id      = $eleicao_id;
                $model->cargo_id        = 1;
                $model->urna_id         = 1;
                $model->created         = date('Y-m-d H:i:s');
                $model->isNewRecord     = true;
                $model->save();  
            } 

            Yii::$app->session->setFlash('voto-success', 'Voto gravado com sucesso!');
            return $this->redirect(['/site/index']);

        } else {

            return $this->render('votacao', [
                'model'         => $model,
                'eleicao_id'    => $eleicao_id,
                'min_voto'      => $min_voto,
                'max_voto'      => $max_voto,
            ]);

        }

    }

I managed to do it like the code below and I also needed to insert $ model-> validate () in the controller

public function rules()
    {
        return [
        ....
        ['candidato_id', 'validarVoto'],
        ....   
        ];
    }

public function validarVoto($attribute, $params, $validator){
    if(count($this->candidato_id) < $min and count($this->candidato_id) > $max){
        $this->addError($attribute, 'Error message');
    }
}

Hi Gugoan,

You can use number validation there

['input_attr', 'number', 'min' => 5, 'max' => 6 ]

For more reference: https://www.yiiframework.com/doc/guide/2.0/en/tutorial-core-validators#number