Yii validation rules for an array

Is there a way to require an array of elements in the rules() method of the Yii model? For instance:

 public function rules() { return array( array('question[0],question[1],...,question[k]','require'), ); } 

I worked in situations where I need to check several arrays of elements based on the form, and I can not find a good way to get around this, except to do the above. I have the same problem when specifying attributeLables() . If anyone has any advice or a better way to do this, I would really appreciate it.

+6
source share
2 answers

You can use CTypeValidator with an alias of type

 public function rules() { return array( array('question','type','type'=>'array','allowEmpty'=>false), ); } 
+13
source

With array('question','type','type'=>'array','allowEmpty'=>false), you can simply verify that you are receiving the exact array, but you do not know what is inside this array. To check the elements of an array, you should do something like:

 <?php class TestForm extends CFormModel { public $ids; public function rules() { return [ ['ids', 'arrayOfInt', 'allowEmpty' => false], ]; } public function arrayOfInt($attributeName, $params) { $allowEmpty = false; if (isset($params['allowEmpty']) and is_bool($params['allowEmpty'])) { $allowEmpty = $params['allowEmpty']; } if (!is_array($this->$attributeName)) { $this->addError($attributeName, "$attributeName must be array."); } if (empty($this->$attributeName) and !$allowEmpty) { $this->addError($attributeName, "$attributeName cannot be empty array."); } foreach ($this->$attributeName as $key => $value) { if (!is_int($value)) { $this->addError($attributeName, "$attributeName contains invalid value: $value."); } } } } 
+2
source

All Articles