2013-02-03 136 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."); 
      } 
     } 
    } 
}