Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii validation rules for an array

Tags:

php

yii

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

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

I have been running into situations where I need to validate several arrays of elements coming from a form and I can't seem to find a good way of going about it other than doing the above. I have the same problem when specifying attributeLables(). If anyone has some advice or a better way of doing this I would really appreciate it.

like image 225
dataplayer Avatar asked Feb 03 '13 09:02

dataplayer


2 Answers

You can use the CTypeValidator aliased by type

public function rules()
{
   return array(
            array('question','type','type'=>'array','allowEmpty'=>false),
   );
}
like image 183
dInGd0nG Avatar answered Oct 12 '22 15:10

dInGd0nG


With array('question','type','type'=>'array','allowEmpty'=>false), you can just verify that you receive exactly array, but you don't know what inside this array. To validate array elements 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.");
            }
        }
    }
}
like image 44
cn007b Avatar answered Oct 12 '22 13:10

cn007b