【问题标题】:ZF2 how to set message of required field when it's empty?ZF2 为空时如何设置必填字段的消息?
【发布时间】:2014-11-15 01:04:46
【问题描述】:

我有一个输入过滤器...

    $this->inputFilter->add($factory->createInput([
        'name' => 'reason',
        'required' => true,
        'filters' => [
            [
                'name' => 'StripTags'
            ]
        ],
        'validators' => [
            [
                'name' => 'StringLength',
                'options' => [
                    'min' => 10,
                    'max' => 150
                ]
            ]
        ]
    ]));

当长度为 0 时,会出现“必需”错误(似乎使用了 NotEmpty 验证器。)这会给出一个非常通用的消息“值是必需的,不能为空。”

由于我在表单上方的列表中而不是在其输入旁边显示所有错误,因此这不够具体。

我假设在验证器数组中有一个“消息”键,但我找不到任何文档。

如何为空输入设置消息?

【问题讨论】:

    标签: php zend-framework2


    【解决方案1】:

    我挖掘了 InputFactory 代码,发现了一些东西......

    continue_if_empty 将允许一个空字段并仍然运行验证器。

        $this->inputFilter->add($factory->createInput([
            'name'     => 'reason',
            'continue_if_empty' => true,
            'filters' => [
                [
                    'name' => 'StripTags'
                ]
            ],
            'validators' => [
                [
                    'name' => 'StringLength',
                    'options' => [
                        'min' => 10,
                        'max' => 150,
                        'messages' => [
                            \Zend\Validator\StringLength::TOO_SHORT => 'The reason must be greater than %min% characters.',
                            \Zend\Validator\StringLength::TOO_LONG => 'The reason must be less than %max% characters.'
                        ]
                    ]
                ]
            ]
        ]));
    

    您还可以添加 error_message 配置。无论发生什么,它似乎总是会显示此错误而不会显示其他错误。这很好,因为唯一的验证器是 StringLength。

        $this->inputFilter->add($factory->createInput([
            'name'     => 'reason',
            'error_message' => 'The reason must be between 10 and 150 characters in length.',
            'filters' => [
                [
                    'name' => 'StripTags'
                ]
            ],
            'validators' => [
                [
                    'name' => 'StringLength',
                    'options' => [
                        'min' => 10,
                        'max' => 150,
                    ]
                ]
            ]
        ]));
    

    如果您仍然需要“非空”消息,您应该能够添加 NotEmpty 验证器,自定义其消息,并使用 continue_if_empty => true 配置。

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 1970-01-01
      • 2017-04-18
      • 2014-08-07
      • 2015-07-01
      • 1970-01-01
      • 2019-07-23
      • 2013-07-07
      • 2012-05-28
      相关资源
      最近更新 更多