簡體   English   中英

如何始終在ZF2驗證器中顯示單個驗證消息?

[英]How to always show single validation message in ZF2 validators?

我有以下輸入:

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;
}

但是,放置一個空的日期,我得到的錯誤消息定義為:Date :: INVALID_DATE

但這不是被覆蓋的。 break_chain_on_failure適用於我定義的兩個驗證器,但是默認的Zend消息始終存在。 例如,我將其作為表單錯誤:

The input does not appear to be a valid date
astropay_invalid_birth_date_18

如何只顯示被覆蓋的錯誤消息,一次僅顯示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!',
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM