dataplayer
dataplayer

Reputation: 73

Yii validation rules for an array

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.

Upvotes: 7

Views: 12406

Answers (2)

cn0047
cn0047

Reputation: 17071

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.");
            }
        }
    }
}

Upvotes: 2

dInGd0nG
dInGd0nG

Reputation: 4114

You can use the CTypeValidator aliased by type

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

Upvotes: 13

Related Questions