Cakephp-3条件notEmpty验证行为

时间:2015-09-01 15:28:52

标签: validation cakephp cakephp-3.0

我需要对字段进行条件验证: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不会运行任何我的验证,因为它&# 39;空了,允许这样。如果我没有注意到该字段可以为空,那么Cake就会运行" notEmpty"在我的自定义验证和输出之前验证"此字段不能留空#34;它什么时候都是空的。

我如何让Cake通过我的条件" notEmpty"验证

我确实尝试过验证规则' on'条件具有相同的结果。

1 个答案:

答案 0 :(得分:0)

已成功测试,这可能对您和其他人有帮助。 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
                    }
                }
            });

在此示例中,Event Date不能为空if position = 1。您必须设置此条件if (!empty($context['data']['position'])),因为只有在用户单击 submit (提交)按钮之后,$context['data']['position']值才会存在。否则,您将得到notice error