我需要对一个字段进行条件验证: if other_field = 1,然后是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;
}
}麻烦的是,如果我注意到,在方法的开头,字段被允许为空,当输入的值为空时,Cake不会运行我的任何验证,因为它是空的,并且允许是空的。如果我没有注意到字段可以是空的,那么Cake只是在我的自定义验证之前运行"notEmpty“验证,并在它为空时输出”这个字段不能一直保持为空“。
如何让Cake通过有条件的"notEmpty“验证?
我确实尝试了使用“on”条件的验证规则,结果也是一样的。
发布于 2019-02-20 06:49:42
测试成功,这可能对您和其他人有帮助。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
}
});在本例中,Event Date不能是空的if position = 1。必须将此条件设置为if (!empty($context['data']['position'])),因为$context['data']['position']值仅在用户单击submit按钮后才会存在。否则,您将得到notice error。
https://stackoverflow.com/questions/32335497
复制相似问题