Custom validator checking number of choices in javascript

Hi,

I’ve created a custom validator which checks number of choices in a multiple select box, here’s the code:




<?php


namespace common\validators;


use yii\validators\Validator;


class MultipleValidator extends Validator

{

    public $count;


    public $min;


    public $max;


    public $message;


    /**

     * @inheritdoc

     */

    public function init()

    {

        parent::init();

        if (is_array($this->count)) {

            if (isset($this->count[0])) {

                $this->min = $this->count[0];

            }

            if (isset($this->length[1])) {

                $this->max = $this->count[1];

            }

            $this->count = null;

        }


        if ($this->min !== null && $this->max !== null && $this->message === null) {

            $this->message = "Select between ".$this->min." and ".$this->max." choices.";

        } elseif ($this->min !== null && $this->message === null) {

            $this->message = "Select at least ".$this->min." choices.";

        } elseif ($this->max !== null && $this->message === null) {

            $this->message = "Select up to ".$this->max." choices.";

        }


    }


    public function validateAttribute($model, $attribute)

    {

        $value = $model->$attribute;


        if (!is_array($value)) {

            $this->addError($model, $attribute, "Selection is not valid.");


            return;

        }


        $count = count($value);


        if (($this->min !== null && $count < $this->min) || ($this->max !== null && $count > $this->max)) {

            $this->addError($model, $attribute, $this->message);

        }

    }


    

}



This works fine, but I don’t know how to do it for javascript validation too. Core validators don’t have anything like this, nor does the javascript active form validator. I could probably sort this, but find it interesting that noone needs this kind of validator (google doesn’t show any examples.

Anyone can help or has built it already?

Thanks

Hi, you see the $whenClient property of validator class.

http://www.yiiframework.com/doc-2.0/yii-validators-validator.html#$whenClient-detail

Yes, I’ve seen it, but don’t see how it helps me. It’s just a conditional validator, which is applied if another field is of certain value. Let’s say I just have one field:




<select multiple="true" name="Model[]">

<option value=1>1</option>

<option value=2>2</option>

<option value=3>3</option>

<option value=4>4</option>

<option value=5>5</option>

</select>



Note that I use ActiveForm’s active field for dropdown list.

How can I dynamically check that a max of # choices is selected?