2016-09-12 5 views
1

나는 그와 같은 방식으로 유효성을 검사하고자하는 모델의 속성을 가졌습니다. 배열이어야하고 배열 내에있는 모든 요소가 문자열이어야하는 3 개의 요소가 있어야합니다. 현재 사용하고 있습니다.배열에 대한 Yii2 유효성 검사 규칙

['config', 'each', 'rule' => ['string']] 

답변

1

사용자 정의 유효성 검사기 (예 : :

['config', function ($attribute, $params) { 
    if(!is_array($this->$attribute) || count($this->$attribute)!==3){ 
     $this->addError($attribute, 'Error message'); 
    } 
}], 
['config', 'each', 'rule' => ['string']] 

creating validators에 대해 자세히 알아보십시오.

0

아래처럼 customvalidation 규칙을 추가 할 수 있습니다

public function rules() 
    { 
    return ['config','checkIsArray']; 

    } 



    public function checkIsArray($attribute, $params) 
     { 
      if (empty($this->config)) { 
       $this->addError('config', "config cannot be empty"); 
      } 
      elseif (!is_array($this->config)) { 
       $this->addError('config', "config must be array."); 
      } 
      elseif (count($this->config)<3) { 
       $this->addError('config', "config must have 3 elements"); 
      } 
      else{ 
      foreach ($this->config as $value) { 
       if (!is_string($value)) { 
        $this->addError('config ', "config should have only string values."); 
       } 
      } 
     } 
    } 
관련 문제