cakephp模型中的条件验证

cakephp模型中的条件验证,cakephp,cakephp-2.0,Cakephp,Cakephp 2.0,我想要条件validiaton,当更新我的密码字段是隐藏的,密码验证是“6到15”个字符!所以密码是以散列格式存储在数据库中的,所以它不允许我更新。我的型号代码如下: <?php class User extends AppModel { public $belongsTo = array( 'Group', 'City', 'Area', ); public $validate = array(

我想要条件validiaton,当更新我的密码字段是隐藏的,密码验证是“6到15”个字符!所以密码是以散列格式存储在数据库中的,所以它不允许我更新。我的型号代码如下:

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

}

您可以有多个validates数组,并在保存之前选择要使用的数组:

在模型中:

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

public $validateWithPassword = array(
   // validation rules including password validation
);
现在,在控制器操作中,您可以选择使用以下密码字段进行验证:

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

问题是什么?您是否需要验证规则来确保密码在6到15个字符之间?或者其他什么?您可能还想使用字段别名作为密码,如下所述:-使您的生活更加轻松现在实际上有一个内置的机制:,尽管我个人认为直接处理
$validate
更容易阅读。不过,值得一提的是。