CakePHP 3.x: how to change the validation rule on the fly

I cannot figure out how to edit an on-the-fly validation rule, for example, in my controller.

My case: the "users" table has an "email" field, the value of which must be "unique" when creating and updating. This is normal at the moment, I created the correct validation rules.

But now I need to create an action that allows users to reset their password. Thus, there is a form in which users enter their email address, and this form needs to be verified. After that, the action checks for the presence of this email address and sends an email to the reset address.

So: I have to validate the form using validation rules, but in this particular case I don’t need the email to be “unique”.

How to change a validation rule for only one action?

Thanks.


EDIT

Maybe this?

class UsersTable extends Table { public function validationDefault(\Cake\Validation\Validator $validator) { //Some rules... $validator->add('email', [ 'unique' => [ 'message' => 'This value is already used', 'provider' => 'table', 'rule' => 'validateUnique' ] ]); //Some rules... return $validator; } public function validationOnlyCheck(\Cake\Validation\Validator $validator) { $validator->remove('email', 'unique'); return $validator; } } 

In my action:

 $user = $this->Users->newEntity($this->request->data(), [ 'validate' => 'OnlyCheck' ]); 
+6
source share
1 answer

What do you have in your question after your Editing is the intended way in which CakePHP 3 allows you to use different / dynamic validation rules in each case.

 use Cake\Validation\Validator; class UsersTable extends Table { public function validationDefault(Validator $validator) { //Some rules... $validator->add('email', [ 'unique' => [ 'message' => 'This value is already used', 'provider' => 'table', 'rule' => 'validateUnique' ] ]); //Some rules... return $validator; } public function validationOnlyCheck(Validator $validator) { $validator = $this->validationDefault($validator); $validator->remove('email', 'unique'); return $validator; } } 

And then:

 $user = $this->Users->newEntity($this->request->data(), [ 'validate' => 'OnlyCheck' ]); 
+8
source

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


All Articles