如何在蛋糕3中创建自定义验证规则

Bob*_*Bob 6 cakephp-3.0

我正在开发Cake 3.我想创建一个自定义验证规则.我想检查字段'password'是否等于'confirm_password'字段.

这是我的代码:

 public function validationDefault(Validator $validator) {
        $validator
                ->add('id', 'valid', ['rule' => 'numeric'])
                ->allowEmpty('id', 'create')
                ->add('email', 'valid', ['rule' => 'email'])
                ->requirePresence('email', 'create')
                ->notEmpty('email')
                ->add('email', 'unique', ['rule' => 'validateUnique', 'provider' => 'table'])
                ->requirePresence('password', 'create')
                ->notEmpty('password')
                ->notEmpty('confirm_password')
                ->add('confirm_password', 'custom', [
                    'rule' => function($value, $context) {
                        if ($value !== $context['data']['password']) {
                            return false;
                        }
                        return false;
                    },
                    'message' => 'The passwords are not equal',
        ]);

        return $validator;
    }
Run Code Online (Sandbox Code Playgroud)

当我尝试'失败'表单提交时,代码保存,我没有错误.

我阅读http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules但没有帮助....任何人?

谢谢!

lor*_*key 18

使用CakePHP 3验证比较两个密码的另一种内置方法可能是:

->add('confirm_password',
    'compareWith', [
        'rule' => ['compareWith', 'password'],
        'message' => 'Passwords not equal.'
    ]
)
Run Code Online (Sandbox Code Playgroud)

您还可以validationDefault在表定义中将其添加到您的方法中.


Bob*_*Bob 3

好吧,我自己找到了。对于所有坚持蛋糕模型的人:永远不要忘记将您的字段添加到$_accessible实体中的数组中!

我的代码:

    /UsersTable.php;

    $validator->add('confirm_password', 'custom', [
        'rule' => function ($value, $context) {
            return false; // Its ment to go wrong ;)
        },
        'message' => 'Password not equal',
    ]);

    /User.php;

    protected $_accessible = [
        'email'            => true,
        'password'         => true,
        'bookmarks'        => true,
        'role_id'          => true,
        'confirm_password' => true,
    ];
Run Code Online (Sandbox Code Playgroud)