Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3.x Custom Validation Rules Creation and Using

In cakephp3 Custom Validation Rules:

How to Use a global function validation method.

$validator->add('title', 'custom', [
    'rule' => 'validate_title'
]);

Please any one done before? Pls Provide me the some example program.

http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules

I tried the above but it doesn't work..?

like image 942
Prassanna D Manikandan Avatar asked Oct 20 '15 09:10

Prassanna D Manikandan


2 Answers

here is an Example for validation using global function concept:

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

    public function validationDefault(Validator $validator) {
        $validator->add('title',[
        'notEmptyCheck'=>[
        'rule'=>'notEmptyCheck',
        'provider'=>'table',
        'message'=>'Please enter the title'
         ]
        ]);
       return $validator;
    }

    public function notEmptyCheck($value,$context){
        if(empty($context['data']['title'])) {
            return false;
        } else {
            return true;
        }
    }
like image 119
Ananthaselvam P Avatar answered Oct 04 '22 00:10

Ananthaselvam P


<?php

namespace App\Model\Table;

use App\Model\Entity\Member;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class MembersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->table('members');
    }

    public function validationDefault(Validator $validator) {
        $validator
                ->add("cedula", [
                    "custom" => [
                        "rule" => [$this, "customFunction"], //add the new rule 'customFunction' to cedula field
                        "message" => "Enter the value greater than 1000"
                    ]
                        ]
                )
                ->notEmpty('cedula');
        return $validator;
    }

    public function customFunction($value, $context) {
        return $value > 1000;
    }

}

Use $context variable to comare current value with other fields like $value >= $context['data']['another_field_name'];

?>

Use $context variable to comare current value with other fields like $value >= $context['data']['another_field_name'];

like image 28
karthik Avatar answered Oct 04 '22 00:10

karthik