繁体   English   中英

CakePHP 4:表单验证回调在不应该执行时执行

[英]CakePHP 4: Form validation callback executes when it's not supposed to

每个人。 我在一个表单中有两个字段,一个下拉列表和一个文本:

echo $this->Form->control('label_id', ['label' => 'Sensitivity Label', 'empty' => true, 'options' => $labels]);
      
echo $this->Form->control('distro_notes', ['label' => 'Distribution Notes (Required if a PROPRIETARY or CONFIDENTIAL label is chosen)']);

仅当从下拉列表中选择某些 label 类型时,才需要字段distro_notes 有六个可用,前两个不需要distro_notes 我的验证规则如下所示:

$validator
    ->notEmptyString('distro_notes', 'This field is required if a PROPRIETARY or CONFIDENTIAL label is chosen', function ($context) {
        $labelIds = [1,2];
        return !in_array($context['data']['label_id'], $labelIds) && empty($context['data']['distro_notes']);
    });

So the validation should only execute when the chosen label ID is 3,4,5, or 6 AND when distro_notes is empty, but it executes in all cases. 我错过了什么?

验证器中的回调 function 应该只返回何时运行此验证器,而不是定义验证规则。 根据 function 定义:

 * @param bool|string|callable $when Indicates when the field is not allowed
 *   to be empty. Valid values are false (never), 'create', 'update'. If a
 *   callable is passed then the field will be required to be not empty when
 *   the callback returns true.

如果您希望distro_notes字段仅在label_id不是1 或 2 时不为空,那么您应该在回调中定义这么多:

$validator->notEmptyString('distro_notes',
    'This field is required if a PROPRIETARY or CONFIDENTIAL label is chosen',
    function ($context) {
        $labelIds = [1, 2];

        return !in_array($context['data']['label_id'], $labelIds);
    });

这样,如果label_id为 1 或 2,则 function 在 label_id 为 1 或 2 时返回false ,然后验证器不会运行(换句话说,如果 label_id 为 1 或 2,则 distro_notes 可以为空)。 然后如果label_id是任何其他值 (3,4,5,6),则distro_notes是必需的,并且不能为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM