数组的 Yii 验证规则


Yii validation rules for an array

有没有办法在 Yii 模型的 rules() 方法中要求元素数组?例如:

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

我一直遇到需要验证多个元素数组的情况来自一种形式,除了做上述事情之外,我似乎找不到一种好的方法。我在指定attributeLables()时遇到了同样的问题.如果有人有一些建议或更好的方法,我将不胜感激。

您可以使用别名CTypeValidator type

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

使用 array('question','type','type'=>'array','allowEmpty'=>false),,您可以验证是否准确接收了数组,但您不知道此数组中的内容。要验证数组元素,您应该执行以下操作:

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