3

我正在使用 ZF2 表单验证。我必须验证两个字段 USERNAME 和 PASSWORD。一切正常,但我收到消息

Please enter username.
Username can not be less than 3 characters.

Please enter password.
Password can not be less than 6 characters.

如果用户未输入任何值,则应仅显示此消息

Please enter username.    
Please enter password.

我不想在失败的字段上显示所有错误消息。

提前致谢。

4

3 回答 3

6

我得到了答案:为了打破 ZF2 中的验证链,我们必须使用

'break_chain_on_failure' => 真

$this->add(
    array(
        'name'       => 'usernmae',
        'required'   => true,
        'filters'    => array(
            array('name' => 'Zend\Filter\StringTrim')
        ),
        'validators' => array(
                          array('name' => 'NotEmpty', 
                            'options' => array('encoding' => 'UTF-8', 
                                'messages' => array(
                                    NotEmpty::IS_EMPTY => 'Please enter username')), 
                            'break_chain_on_failure' => true), 
            array(
                'name'    => 'Zend\Validator\StringLength',
                'options' => array(
                    'encoding' => 'UTF-8',
                    'min'      => 3,
                    'max'      => 30,
                    'messages' => array(
                                    StringLength::TOO_LONG => 'Username can not be more than 30 characters long', 
                                    StringLength::TOO_SHORT => 'Username can not be less than 3 characters.')
                ),
                'break_chain_on_failure' => true
            )
        )
    )
);

我的博客: http: //programming-tips.in

于 2013-03-28T10:28:36.940 回答
1

Zend_Validate 允许您在某些验证失败时中断验证器链。在这种情况下,addValidator() 函数 $breakChainOnFailure 的第二个参数应该为 TRUE。

$validatorChain = new Zend_Validate();    
$validatorChain->addValidator(new Zend_Validate_NotEmpty(), TRUE)
               ->addValidator(new Zend_Validate_StringLength(6, 12));
于 2013-03-28T09:51:27.513 回答
0

您还可以设置“error_message”键,例如:

'email' => [
                'required' => true,
                'error_message' => 'Incorrect email address ',
                'filters' => [
                    [
                        'name' => 'StripTags',
                    ],
                    [
                        'name' => 'StringToLower',
                    ]
                ],
                'validators' => [
                    [
                        'name' => 'EmailAddress',
                        'break_chain_on_failure' => true
                    ]
                ]
            ],
于 2016-12-02T20:07:29.313 回答