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