Cakephp-3条件notEmpty验证行为
发布时间:2020-12-13 22:23:37 所属栏目:PHP教程 来源:网络整理
导读:我需要对字段进行条件验证:如果other_field = 1则this_field = notBlank.我找不到办法做到这一点. 我在表类中的验证器: public function validationDefault(Validator $validator) { $validator-allowEmpty('inst_name'); $validator-add('inst_name',[ 'n
我需要对字段进行条件验证:如果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’条件的验证规则,结果相同. 解决方法
成功测试,这可能会帮助您和其他人. CakePHP 3. *
$validator->notEmpty('event_date','Please enter event date',function ($context) { if (!empty($context['data']['position'])) { if ($context['data']['position'] == 1) { return true; // <-- this means event date cannot be empty if position value is 1 } } }); 在此示例中,如果position = 1,则Event Date不能为空.你必须把这个条件设置为(!empty($context [‘data’] [‘position’]))因为$context [‘data’] [‘position’]值仅在用户点击提交按钮后才存在.否则你会收到通知错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |