Home » Php » php – Yii validation rules for an array

php – Yii validation rules for an array

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

You can use the CTypeValidator aliased by type

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

Answer:

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