Answer the question
In order to leave comments, you need to log in
How to properly validate a field in yii2?
Good day!
I have a form with a multiple choice of cities
. I added [] so that an array of id cities comes to my server, how to properly validate this array, if you simply specify cities, one value will come, otherwise yii swears that it cannot find such a field cities[].
,
Answer the question
In order to leave comments, you need to log in
['cities', function ($attribute, $params, $validator) {
if(is_array($this->$attribute)) {
if(empty($this->$attribute)) {
$this->addError($attribute, 'The array shouldnt be empty');
}
foreach($this->$attribute as $item) {
if(!is_int($item)) {
$this->addError($attribute, 'The array contains not an integer values');
break;
}
}
}
}],
[
['cities', 'each', 'rule' => ['required']],
['cities', 'each', 'rule' => ['integer']],
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question