2013-02-03 139 views
6

有没有办法在Yii模型的rules()方法中需要一组元素? 例如:Yii数组验证规则

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

我一直运行到哪里,我需要验证元素的多个阵列的情况 从表单来了,我似乎无法找到比做绕了其他的好办法以上。指定attributeLables()时,我遇到同样的问题。如果任何人有一些建议或更好的方式做到这一点,我会非常感激。

+0

dlnGd0nG,链接没有提及如何验证元素的数组。 – dataplayer

+0

我以为你想添加表格输入。那些问题[x]'是什么?他们是否是阶级属性?并通过Yii模式,你指的是什么? 'CActiveRecord','CfromModel'或'CModel'? – dInGd0nG

+0

dlnGd0nG,'question [x]'是我提交的表单的名称值。我提到的Yii模型特别是CFormModels。 – dataplayer

回答

13

可以使用CTypeValidator别名通过type

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

这就是我一直在寻找的东西。我只是用'type'别名,就像你提到的那样:'array('question','CTypeValidator','type'=>'array','allowEmpty'=> false),'它的工作很完美。谢谢! – dataplayer

2

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