2013-01-17 136 views
0

使用CakePHP 1.3我開發了博客引擎,包含帖子和評論表,最近我注意到在數據庫中,儘管Comment模型已經定義了內容列中的空值適當的驗證:在模型中定義的驗證 - CakePHP



    <?php 
    class Comment extends AppModel { 
     var $name = 'Comment'; 
     var $sequence = 'comments_seq'; 

     var $belongsTo = array(
      'Post' => array(
       'className' => 'Post', 
       'foreignKey' => 'post_id' 
      ) 
     ); 

     var $validate = array(
      'content' => array(
       'required' => array (
         'rule' => 'notEmpty', 
         'message' => 'Content can't be empty.' 
       ) 
      ), 
      'post_id' => array(
       'rule' => 'notEmpty' 
      ), 
      'created' => array(
       'rule' => 'notEmpty' 
      ) 
     ); 
    ?> 

在上面定義的CakePHP框架或驗證中是否有錯誤是不正確或不足?

回答

2

在您的驗證規則中,您實際上並不需要該字段。要求意味着密鑰在驗證時必須存在。 notEmpty規則只要求密鑰是非空但不是存在

若要求的字段存在,請使用您的驗證規則所需的選項:

var $validate = array(
    'content' => array(
    'required' => array (// here, 'required' is the name of the validation rule 
     'rule' => 'notEmpty', 
     'message' => 'Content can\'t be empty.', 
     'required' => true // here, we say that the field 'content' must 
         // exist when validating 
    ) 
), 
    'post_id' => array(
    'rule' => 'notEmpty' 
    ), 
    'created' => array(
    'rule' => 'notEmpty' 
    ) 
); 

如果沒有必要的關鍵,你可能會被保存時,根本不包括「內容」鍵保存完全空記錄。現在需要,如果'內容'不在您保存的數據中,驗證將失敗。

+0

確實。這是我的錯;/ –

+0

「allowEmpty」鍵,「必需」鍵和「notEmpty」規則之間的區別起初有點難以理解:) – jeremyharris