2012-05-28 86 views
2

嘿傢伙有一個Cakephp驗證的問題..Cakephp驗證問題

我想知道爲什麼partytwo驗證會直接到false?

這裏是我的關係模型:

<?php 
    class Relationship extends AppModel{ 
     var $name='Relationship'; 
     public $useTable = 'relationships_users'; 
     public $primaryKey = 'id'; 

     var $validate = array(
      'date' => array(
       'rule' => array('datevalidation', 'systemDate'), 
       'message' => 'Current Date and System Date is mismatched' 
      ), 
      'partytwo'=>array(
       'partytwoExists'=>array(
        'rule'=> 'userExists', 
        'message'=>'That username doesnt exist.' 
       ) 
      ) 
     ); 

     function datevalidation($field=array(), $compare_field=null) { 
      if ($field['date'] > $compare_field) 
       return TRUE; 
      else 
       return FALSE; 
     } 

     function userExists($check) { 
      $userExists= $this->find('count', array('conditions'=>$check)); 
      if($userExists == 1) { 
       return TRUE; 
      }else{ 
       return FALSE; 
      } 
     } 
... 
+1

那麼,無論如何,你的'$ check'參數是什麼? –

+0

'$ check'包含你想要驗證的字段。 '$ this-> data'包含您要驗證/保存的當前數據。考慮到這一點,更新您的代碼。您在userExists方法中的目標是檢查您的數據中是否存在用戶標識。 – tigrang

回答

1

根據CakePHP的書Adding Your Own Validation Methods部分,是寫了這樣

'rule' => array('datevalidation', 'systemDate') 

自定義規則意味着蛋糕將運行在您的datevalidation方法是這樣的:

$valid = $Relationships->datevalidation(array(
    'date' => 'some user input value' 
), 'systemDate'); 

用同樣的方式,

'rule' => array('userExists') 

導致蛋糕運行

$valid = $Relationships->userExists(array(
    'partytwo' => 'some user input value' 
)); 

(模擬電話。實際調用是使用dispatchMethod在Model.php的line 3155

那麼,你是最有可能需要重寫你的datevalidation方法。此外,你的代碼

$userExists= $this->find('count', array('conditions'=>$check)); 

$userExists可以返回你一個數大於或等於0。您的邏輯是錯誤的,如果返回2以上。改爲考慮Model::hasAny。這可能是它爲什麼總是被驗證爲false您的情況。