2014-03-27 72 views
2

假設我有一打單選按鈕字段,我想根據兩條常用規則進行驗證。CakePHP - 使用相同規則驗證多個字段

'valid'=> array(
     'rule' => array('inList', array('yes','no')), 
     'message' => 'Illegal Choice Detected' 

    ), 
    'required'=> array(
     'rule' => array('notEmpty'), 
     'message' => 'Field is required.' 
    ), 

如何在不必爲每個字段分配每個驗證規則的情況下執行此操作?

[編輯]

對於如何喜歡一些勺子餵養,因爲我自己喜歡有時,這裏是我是如何做到的基礎上問:Burzum的答案!

public function beforeValidate($options = []) { 
     $fields = ['field_1','field_2','field_3','etc']; 
     foreach ($fields as $field) {    
      $this->validate[$field]['required'] = array(
        'rule' => array('notEmpty'), 
        'message' => 'Field is required.' 
      ); 
      $this->validate[$field]['legal'] = array(
        'rule' => array('inList', array('yes', 'no')), 
        'message' => 'An illegal choice has been detected, please contact the website administrator.' 
      ); 
     } 
     return true; 
    } 

回答

4

加入他們在beforeValidate foreach循環()

public function beforeValidate($options = []) { 
    $fields = ['field1', '...']; 
    foreach ($fields as $field) { 
     // Add your rule(s) here to the field 
     $this->validate[$field]['myRule'] = ['...']; 
    } 
    return true; 
} 
+0

即期。這聽起來很不錯!我會給它一槍!謝謝一堆 – LogixMaster

相關問題