TrinityTuts Tips

Set validation on run time cakephp3

Last updated on April 12th, 2018 at 05:49 pm

This is very simple and tested method of validation you can use in your project. Some time we need to add validation on fly in our controller then at that case you can use this code.

use Cake\Validation\Validator;

$validator = new Validator();
$validator
                ->notEmpty('file', 'Select file to upload')
                ->add('file', [
                    'validExtension' => [
                        'rule' => ['extension',['png']],
                        'message' => __('These files extension are allowed: .png')
                    ]
                ]);
$errors = $validator->errors($this->request->data());

And second method is much easier than above technique you need to create custom method in your Model like below and define all rule

public function validationFileUpload($validator)
    {
        $validator
                ->notEmpty('file', 'Select file to upload')
                ->add('file', [
                    'validExtension' => [
                        'rule' => ['extension',['png']],
                        'message' => __('These files extension are allowed: .png')
                    ]
                ]);
        return $validator;
    }

and you can call this where you can create entity in your controller.

$product = $this->Products->patchEntity($product, $this->request->data, ['validate' => 'FileUpload']);

Hope this tip help you to create run time validation in your cakephp 3 application 🙂

CakePHP 3 custom validation