2012-11-07 54 views
2

我希望在更新密碼字段的同時隱藏密碼字段並且密碼驗證是'6到15個字符之間!所以密碼以散列格式存儲在數據庫中,所以不允許我更新。我的模型代碼如下,在cakephp模型中進行條件驗證

<?php 
class User extends AppModel { 

    public $belongsTo = array(
     'Group', 
     'City', 
     'Area', 
    ); 

    public $validate = array(
     'name' => array(
      'rule'  => 'alphaNumeric', 
      'required' => true, 
      'message' => 'Only alphabets and numbers are allowed!' 
     ), 
     'email' => array(
      //~ 'rule1' => array(
       //~ 'rule' => 'isUnique', 
       //~ 'message' => 'Email address already exists!', 
       //~ 'last' => true 
      //~), 
      'rule2' => array(
       'rule' => 'email', 
       'message' => 'Invalid Email!', 
       'last' => true 
      ) 
     ), 
     //~ 'password' => array(
       //~ 'rule' => array('between', 6, 15), 
       //~ 'required' => true, 
       //~ 'message' => 'Password must be of 6 to 15 characters' 
     //~), 
     //~ 'confirm_password' => array(
      //~ 'rule' => 'confirmPassword', 
      //~ 'message' => 'Confirm password do not match!' 
     //~), 
     //~ 'address' => array(
      //~ 'allowEmpty' => false, 
      //~ 'required' => true, 
      //~ 'message' => 'Description is required' 
     //~), 
     //~ 'phone_number' => array(
      //~ 'rule' => 'phone', 
      //~ 'allowEmpty' => false, 
      //~ 'required' => true, 
      //~ 'message' => 'Phone Number is required' 
     //~) 
    ); 

    public function beforeSave() { 
     if (isset($this->data[$this->alias]['password'])) { 
      $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']); 
     } 
     return true; 
    } 

    public function confirmPassword() { 
     debug('model'); 
     if ($this->data[$this->alias]['confirm_password'] != '') { 
      debug('model in'); 
      if(strcmp($this->data[$this->alias]['password'], $this->data[$this->alias]['confirm_password']) == 0) { 
       debug('model in in'); 
       return true; 
      } 
     } 
     return false; 
    } 

} 

我也有confrim密碼驗證。所以告訴我任何有條件驗證的解決方案!謝謝你的幫助!

+0

問題是什麼?你是否要求驗證規則以確保密碼在6到15個字符之間?或者是其他東西? – jeremyharris

+0

您可能還想使用字段別名作爲密碼,如下所述:http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/ - 讓您的生活變得輕鬆多了 – mark

回答

6

你可以有一個以上的驗證陣列,然後選擇要保存您之前使用哪一個:模型

:現在

public $validate = array(
    // default validation rules 
); 

public $validateWithPassword = array(
    // validation rules including password validation 
); 

,在你的控制器動作,您可以選擇與驗證密碼字段爲:

$this->User->validate = $this->User->validateWithPassword; 
+1

現在實際上有一個內置的機制:http://book.cakephp.org/2.0/en/models/data-validation.html#dynamically-change-validation-rules,雖然我個人覺得直接處理'$ validate'閱讀起來要容易得多。還是值得一提的。 –