【问题标题】:How to always show single validation message in ZF2 validators?如何始终在 ZF2 验证器中显示单个验证消息?
【发布时间】:2014-11-18 10:22:33
【问题描述】:

我有以下输入:

private function addBirthdayElement()
{
    return $this->add(
        array(
            'type'       => 'DateSelect',
            'name'       => 'x_bdate',
            'options'    => [
                'label'             => 'astropay_birthday',
                'label_attributes'  => array(
                    'class' => 'astropay-label'
                ),
                'create_empty_option' => true,
                'render_delimiters' => false,
            ],
            'attributes' => array(
                'required' => true,
                'class' => 'astropay-input',
            )
        )
    );
}

它有以下过滤器:

public function addBirthdayFilter()
{
    $time = new \DateTime('now');
    $eighteenYearAgo = $time->modify(sprintf('-%d year', self::EIGHTEEN_YEARS))->format('Y-m-d');

    $this->add(
        [
            'name'       => 'x_bdate',
            'required'   => true,
            'validators' => [
                [
                    'name'                   => 'Between',
                    'break_chain_on_failure' => true,
                    'options'                => [
                        'min'      => 1900,
                        'max'      => $eighteenYearAgo,
                        'messages' => [
                            Between::NOT_BETWEEN        => 'astropay_invalid_birth_date_18',
                            Between::NOT_BETWEEN_STRICT => 'astropay_invalid_birth_date_18',
                        ]
                    ]
                ],
                [
                    'name'                   => 'Date',
                    'break_chain_on_failure' => true,
                    'options'                => [
                        'messages' => [
                            Date::INVALID      => 'astropay_invalid_birth_date',
                            Date::FALSEFORMAT  => 'astropay_invalid_birth_date',
                            Date::INVALID_DATE => 'astropay_invalid_birth_date',
                        ],
                    ]
                ],
            ],
        ]
    );

    return $this;
}

但是,输入一个空日期,我收到了为以下定义的错误消息: 日期::INVALID_DATE

但它不是被覆盖的。 break_chain_on_failure 适用于我定义的两个验证器,但默认的 Zend 消息始终存在。例如,我在表单中将此视为错误:

The input does not appear to be a valid date
astropay_invalid_birth_date_18

如何一次只显示覆盖的错误消息和 1 条?

【问题讨论】:

    标签: validation zend-framework2 zend-form


    【解决方案1】:

    您可以在验证器配置中使用 message 键而不是 messages 数组来始终显示每个验证器的一条消息。

    例如,替换这个:

    'options' => [
        'messages' => [
            Date::INVALID      => 'astropay_invalid_birth_date',
            Date::FALSEFORMAT  => 'astropay_invalid_birth_date',
            Date::INVALID_DATE => 'astropay_invalid_birth_date',
        ],
    ]
    

    用这个:

    'options' => [
        'message' => 'Invalid birth date given!',
    ]
    

    【讨论】: