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..?
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;
}
}
<?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'];
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