I cannot figure out how to edit a validation rule on the fly, for example in my controller.
My case: the "users" table has the "email" field, whose value must be "unique" when creating and updating. For now it's ok, I have created the correct validation rules.
But now I have to create an action that allows users to recover their password. So there's a form in which users enter their email address and this form must be validated. After, the action checks if there's that email address and sends an email to reset the password.
So: I have to validate the form with the validation rules, but in this particular case I don't need the email is "unique".
How to change the validation rule only for 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'
]);
What you have in your question after your Edit is the intended way in which CakePHP 3 allows you to use different/dynamic validation rules per use 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'
]);
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