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'];
?>
<?php
namespace App\Form;
use Cake\Form\Form;
use Cake\Validation\Validator;
class addPostForm extends Form {
protected function _buildValidator(Validator $validator) {
return $validator->allowEmpty('my_input', function ($context) {
return (@context['data']['an_other_input'] != "");
});
}
public function setErrors($errors) {
$this->_errors = $errors;
}
}
public function validationDefault(Validator $validator)
{
$validator = new Validator();
$validator
->notEmpty('username', 'A username is required')
->add('username', [
'emailValid' => [
'rule' => ['email', true],
'message' => 'You must provide a valid email'
],
'emailUnique' => [
'message' => 'The email you provided is already taken. Please provide another one.',
'rule' => 'validateUnique',
'provider' => 'table'
]
]);
return $validator;
}
5条答案
按热度按时间gfttwv5a1#
以下是使用全局函数概念进行验证的示例:
6xfqseft2#
使用$context变量将当前值与其他字段进行比较,如$value〉= $context ['data']['another_field_name'];
6l7fqoea3#
这对我来说真的很有用(Cakephp 3.x)。如果你的情况很简单,这是一个很好的方法:
这里表单输入
my_input
只有在第二个输入an_other_input
完成后才允许为空。您可以使用变量$context['data']
获取表单数据。nhaq1z214#
这就是我在CakePHP 3.0中所做的工作。这里的重要参数是'provider',在文档示例中不是很清楚。
然后定义函数。传递给函数的变量为
$check ='标题'
:
wwwo4jvm5#
下面是一个验证示例。
在您的表中。