Ega*_*ega 5 validation cakephp cakephp-3.0
我需要对一个字段进行条件验证: if other_field = 1then this_field = notBlank。我找不到办法做到这一点。我在表类中的验证器:
public function validationDefault(Validator $validator) {
$validator->allowEmpty('inst_name');
$validator->add('inst_name', [
'notEmpty' => [
'rule' => 'checkInstName',
'provider' => 'table',
'message' => 'Please entar a name.'
],
'maxLength' => [
'rule' => ['maxLength', 120],
'message' => 'Name must not exceed 120 character length.'
]
]);
return $validator;
}
public function checkInstName($value, array $context) {
if ($context['data']['named_inst'] == 1) {
if ($value !== '' && $value !== null) {
return true;
} else {
return false;
}
} else {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,如果我注意到,在方法的开头,该字段允许为空,当输入的值为空时,Cake 不会通过我的任何验证,因为它是空的并且允许这样. 如果我没有注意到该字段可以为空,Cake 只会在我的自定义验证之前运行“notEmpty”验证,并在它为空时始终输出“此字段不能为空”。
我如何让 Cake 通过我的条件“notEmpty”验证?
我确实尝试了具有相同结果的“开启”条件的验证规则。
测试成功,这可能会对您和其他人有所帮助。CakePHP 3. *
$validator->notEmpty('event_date', 'Please enter event date', function ($context) {
if (!empty($context['data']['position'])) {
return $context['data']['position'] == 1; // <-- this means event date cannot be empty if position value is 1
}
});
Run Code Online (Sandbox Code Playgroud)
在此示例中Event Date不能为空if position = 1。您必须设置此条件if (!empty($context['data']['position'])),因为$context['data']['position']只有在用户单击提交按钮后该值才会存在。否则你会得到notice error.
| 归档时间: |
|
| 查看次数: |
1484 次 |
| 最近记录: |