How to create your own validation rule in cake 3

I am working on Cake 3. I want to create my own validation rule. I want to check if the password field matches 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 "crash" the form-submit, the code is saved and I get no error.

I read http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules but it didn't help .... Anyone?

Thanks!

+6
source share
4 answers

Ok, I found this on myself. For everyone who is stuck on cake models: NEVER FORGET $_accessible YOUR FIELDS TO $_accessible -array IN YOUR ENTITY!

My code is:

  /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, ]; 
+2
source

Another built-in way to compare two passwords with CakePHP 3 verification can be:

 ->add('confirm_password', 'compareWith', [ 'rule' => ['compareWith', 'password'], 'message' => 'Passwords not equal.' ] ) 

You can also add this to your validationDefault method in a table definition.

+18
source

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.', ]); 
+2
source
 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; } 
0
source

Source: https://habr.com/ru/post/980078/


All Articles