如何在ZF2验证器中始终显示单个验证消息?

时间:2014-11-18 10:22:33

标签: validation zend-framework2 zend-form

我有以下输入:

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?

1 个答案:

答案 0 :(得分: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!',
]