I am working on Cake 3. I want to create a custom validation-rule. I want to check if the field 'password' is equal to the 'confirm_password' field.
This is my code:
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;
}
When I try to 'fail' the form-submit, the code saves, and I get no error.
I read http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules but didn't help.... Anybody?
Thanks!
Another built in way to compare two passwords with CakePHP 3 validation could be:
->add('confirm_password',
'compareWith', [
'rule' => ['compareWith', 'password'],
'message' => 'Passwords not equal.'
]
)
You can also add this to your validationDefault
method in your Table definition.
Okay I've found it on myself. To everybody who stuck on cake's models: NEVER FORGET TO ADD YOUR FIELDS TO THE $_accessible
-array IN YOUR ENTITY!
My code:
/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,
];
Please try this code ,it will work for sure
$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.',
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With