A
A
Andrey Astafiev2019-05-05 10:45:58
Yii
Andrey Astafiev, 2019-05-05 10:45:58

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[].

,

I need that there was only type int and the field was not empty

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Decadal, 2019-05-05
@Astafiev_Andrey

['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; 
        }
     }            
  }
}],

M
Maxim Timofeev, 2019-05-05
@webinar

[
   ['cities', 'each', 'rule' => ['required']],
   ['cities', 'each', 'rule' => ['integer']],
]

https://github.com/yiisoft/yii2/blob/master/docs/g...
mustn't, show the form

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question