CakePHP仅在提供时进行验证

CakePHP仅在提供时进行验证,php,validation,cakephp,passwords,Php,Validation,Cakephp,Passwords,在我的“成员”模型中,我通过此自定义验证密钥/函数对比较密码是否与密码_确认匹配 ...'password_confirm' => array( 'compare' => array( 'rule' => array('validate_passwords'), 'message' => 'The passwords you entered do not match.',

在我的“成员”模型中,我通过此自定义验证密钥/函数对比较
密码
是否与
密码_确认
匹配

...'password_confirm' => array(
        'compare'    => array(
            'rule'      => array('validate_passwords'),
            'message'   => 'The passwords you entered do not match.',
            'required'  => true
        ),

        'length' => array(
            'rule'      => array('between', 6, 20),
            'message'   => 'Your password must be between 6 and 20 characters.',
        ),

        'empty' => array(
            'rule'      => 'notEmpty',
            'message'   => 'The password field must not be left blank.',
        ),
    )...
函数验证密码

function validate_passwords($data, $password_field = 'password', $hashed = true) {
    $password         = $this->data['Member']['password'];
    $password_confirm = $hashed ?
          Security::hash($data['password_confirm'], null, true) :
          $data['password_confirm'];
    return $password === $password_confirm;
}
我的网站有许多不同的部分,允许编辑成员。有些部分允许更改密码,而另一些部分只允许成员编辑他们的个人简历

但是,由于在用户编辑其个人简历的表单中没有“密码确认”字段(例如),因此验证在任何表单上都会返回false,但存在“密码确认”的表单除外

有没有一种有效的方法可以像这样验证

“仅当
$data
数组中存在
password\u confirm
键时,才将password与password\u confirm进行比较”

我在任何地方都找不到这个,所以,我希望我没有重复一个现有的问题

谢谢


注意。如果表单中确实存在该字段,我想确保该字段没有留空。

只要修改
验证密码
函数,如果
['password\u confirm']
字段不存在,则返回true

如果它确实存在,请先检查它是否为
empty()
(如果是,则返回false)

最后,按当前的状态进行其余的检查。

您正在寻找的

'allowEmpty' => true

食谱^^^


关于空验证测试的一些讨论。HTH.

修复了该部分,谢谢,但现在我遇到了内置规则的问题,即它在检查密码长度,即使我没有为其提供要更改的密码。您可能也需要创建自定义长度检查函数。请使用allowEmpty as true确认密码