Cakephp 3.0 如何在cake 3中创建自定义验证规则
我正在做蛋糕3。我想创建一个自定义验证规则。 我想检查“密码”字段是否等于“确认密码”字段 这是我的代码:Cakephp 3.0 如何在cake 3中创建自定义验证规则,cakephp-3.0,Cakephp 3.0,我正在做蛋糕3。我想创建一个自定义验证规则。 我想检查“密码”字段是否等于“确认密码”字段 这是我的代码: public function validationDefault(Validator $validator) { $validator ->add('id', 'valid', ['rule' => 'numeric']) ->allowEmpty('id', 'create')
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;
}
当我尝试“失败”表单提交时,代码会保存,并且不会出现错误
我读了,但没有帮助。。。。有人吗
谢谢 好的,我在自己身上找到了。对于所有坚持使用cake模型的人:永远不要忘记将字段添加到实体中的
$\u可访问的-数组中
我的代码:
/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,
];
使用CakePHP 3验证比较两个密码的另一种内置方法是:
->add('confirm_password',
'compareWith', [
'rule' => ['compareWith', 'password'],
'message' => 'Passwords not equal.'
]
)
您还可以将其添加到表定义中的validationDefault
方法中。请尝试此代码,它肯定会起作用
public function validationResetpassword(Validator $validator){
$validator
->requirePresence('password')
->notEmpty('password','Please enter Password')
->add('confirm_password', [
'compare' => [
'rule' => ['compareWith','password'],
'message' => 'Confirm Password does not match with Password.'
]])
->requirePresence('confirm_password')
->notEmpty('confirm_password','Please enter Confirm Password')
;
return $validator;
}
不适合我:P你做了什么;完全复制了?这是错误的。_accessible属性只允许对给定的属性进行质量分配。我建议您删除其他用户在此访问的已接受答案。与
方法I比较在哪里?您的代码中缺少此内容
$validator
->notEmpty('cpassword')
->add('cpassword', ['length' => ['rule' => ['minLength', 8],'message' => 'Password need to be at least 8 characters long',]])
->add('cpassword', 'passwordsEqual', [
'rule' => function($value, $context) {
return isset($context['data']['cpassword']) &&
$context['data']['password'] === $value;
},
'message' => 'The two password you typed do not match.',
]);