2010-10-22 163 views
5

我有一個自定義驗證規則來檢查輸入的兩個密碼是否相同,如果他們不是我希望有一條消息說「密碼不匹配」。cakephp自定義驗證規則消息

然而,規則的作品,當密碼不匹配它只是顯示正常的錯誤信息,發生了什麼?

var $validate=array(
     'passwd2' => array('rule' => 'alphanumeric', 
         'rule' => 'confirmPassword', 
         'required' => true, 
         'allowEmpty'=>false)); 

function confirmPassword($data) 
{ 
    $valid = false; 
    if (Security::hash(Configure::read('Security.salt') .$data['passwd2']) == $this->data['User']['passwd']) 
    { 
     $valid = true; 
     $this->invalidate('passwd2', 'Passwords do not match'); 
    } 
    return $valid; 
} 

它說:「此字段不能留空」

編輯:

奇怪的是,如果我離開空白密碼的領域之一,雙方的錯誤消息說「此字段不能留空」

但是,如果我把兩個東西,那麼它正確地說:‘密碼不匹配’

回答

6

我覺得你做它太複雜了。下面是我如何做到這一點:

// In the model 
    public $validate = array(
     'password' => array(
      'minLength' => array(
       'rule' => array('minLength', '8') 
      ), 
      'notEmpty' => array(
       'rule' => 'notEmpty', 
       'required' => true 
      ) 
     ), 
     'confirm_password' => array(
      'minLength' => array(
       'rule' => array('minLength', '8'), 
       'required' => true 
      ), 
      'notEmpty' => array(
       'rule' => 'notEmpty' 
      ), 
      'comparePasswords' => array(
       'rule' => 'comparePasswords' // Protected function below 
      ), 
     ) 
    ); 
    protected function comparePasswords($field = null){ 
     return (Security::hash($field['confirm_password'], null, true) === $this->data['User']['password']); 
    } 

// In the view 
echo $form->input('confirm_password', array(
    'label' => __('Password', true), 
    'type' => 'password', 
    'error' => array(
     'comparePasswords' => __('Typed passwords did not match.', true), 
     'minLength' => __('The password should be at least 8 characters long.', true), 
     'notEmpty' => __('The password must not be empty.', true) 
    ) 
)); 
echo $form->input('password', array(
    'label' => __('Repeat Password', true) 
)); 
+0

哦,我不知道,你可以指定錯誤消息的形式幫助選項,這簡化了很多事情! – 2010-10-22 23:22:28

+0

這是在食譜 - http://book.cakephp.org/view/1401/options-error。請注意,「confirm_password」和「密碼」字段的標籤已切換。 – bancer 2010-10-22 23:27:04