验证选中的复选框数量

Validate checked checkbox quantity

我有一张投票表,我想验证每个选民可以投票给的最少和最多候选人数。这些最大值和最小值存储在登录用户的会话中。有什么更好的方法吗?

型号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_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(); ?>

注意:此候选人列表是动态的,根据登录用户的参数加载候选人。

规则测试更新:

public function rules()
    {
        return [
            ['candidato_id', 'validateCandidates','message'=> 'teste'],
        ];
    }

    public function validateCandidates($attribute, $params, $validator){
        if(count($this->candidato_id) >= 4){ // test with value 4
            $this->addError($attribute, 'Error message');
        }
    }

创建自定义验证。像这样:

型号Voto.php

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

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