9
votes

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'
]);
1
To me that sounds as if you should use a separate validator, as this is only about a single field that isn't even ment to be saved?ndm
Thanks @ndm, maybe I can do this: for this specific case, I use a new validator that extends the original one (UserOnlyCheckValidator extends UserValidator). In the new validator, I just only delete that rule. What do think about?Mirko Pagliai
@ndm, see my last editMirko Pagliai

1 Answers

12
votes

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'
]);