2010-10-22 39 views
5

Tôi có quy tắc xác thực tùy chỉnh để kiểm tra xem hai mật khẩu đã nhập có giống nhau hay không và nếu chúng không muốn có thông báo cho biết "Mật khẩu không khớp".cakephp Thông báo quy tắc xác thực tùy chỉnh

Quy tắc hoạt động, tuy nhiên, khi mật khẩu không khớp với nó, chỉ cần hiển thị thông báo lỗi bình thường, điều gì đang xảy ra?

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; 
} 

Nó nói "Lĩnh vực này không thể để trống"

EDIT:

Điều kỳ lạ là, nếu tôi rời khỏi một trong những lĩnh vực mật khẩu trống, cả hai thông báo lỗi nói "Lĩnh vực này không thể được để trống"

Tuy nhiên, nếu tôi đặt một cái gì đó trong cả hai, sau đó nó nói một cách chính xác 'Mật khẩu không khớp nhau'

Trả lời

6

Tôi nghĩ bạn đã làm cho nó quá phức tạp. Đây là cách tôi làm điều đó:

// 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

Oh tôi không biết bạn có thể chỉ định thông báo lỗi như một tùy chọn trong các hình thức trợ giúp, đơn giản hóa mọi thứ rất nhiều! –

+0

Nó có trong sách dạy nấu ăn - http://book.cakephp.org/view/1401/options-error. Lưu ý rằng các nhãn cho các trường 'confirm_password' và 'password' được chuyển đổi. – bancer

Các vấn đề liên quan