繁体   English   中英

Laminas / ZF3:手动将错误添加到字段

[英]Laminas / ZF3: Add manually Error to a field

是否可以在字段验证和输入过滤器之后手动向字段添加错误消息?

如果用户名和密码错误,我需要它来标记这些字段/显示错误消息。

显然在 ZF/ZF2 中可以使用$form->getElement('password')->addErrorMessage('The Entered Password is not Correct'); - 但这在 ZF3/Laminas 中不再起作用

在不知道如何进行验证的情况下(实际上有几种方法),最干净的解决方案是在创建 inputFilter 时设置错误消息(而不是在元素添加到表单后将其设置为元素)。

请记住,表单配置(元素、水合器、过滤器、验证器、消息)应在表单创建时设置,而不是在使用时设置。

此处表单被扩展(使用其输入过滤器),如文档中所示:

use Laminas\Form\Form;
use Laminas\Form\Element;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\NotEmpty;

class Password extends Form implements InputFilterProviderInterface {

    public function __construct($name = null, $options = []) {
        parent::__construct($name, $options);
    }

    public function init() {
        parent::init();

        $this->add([
            'name' => 'password',
            'type' => Element\Password::class,
            'options' => [
                'label' => 'Password',
            ]
        ]);
    }

    public function getInputFilterSpecification() {
        $inputFilter[] = [
            'name' => 'password',
            'required' => true,
            'validators' => [
                [
                    'name' => NotEmpty::class,
                    'options' => [
                        // Here you define your custom messages
                        'messages' => [
                            // You must specify which validator error messageyou are overriding
                            NotEmpty::IS_EMPTY => 'Hey, you forgot to type your password!'
                        ]
                    ]
                ]
            ]
        ];
        return $inputFilter;
    }
}

还有其他方法可以创建表单,但解决方案是相同的。
我还建议你看看laminas-validator 的文档,你会发现很多有用的信息

Laminas Laminas\Form\Element class 有一个名为setMessages()的方法,它需要一个数组作为参数,例如

$form->get('password')
   ->setMessages(['The Entered Password is not Correct']);

请注意,这将清除您的元素可能已有的所有错误消息。 如果你想像旧的addErrorMessage()方法一样添加你的消息,你可以这样做:

$myMessages = [
   'The Entered Password is not Correct',
   '..maybe a 2nd custom message'
];
$allMessages = array_merge(
   $form->get('password')->getMessages(),
   $myMessages);

$form
  ->get('password')
  ->setMessages($allMessages);

您还可以使用错误模板名称 Laminas 用于其错误消息作为消息数组中的键来覆盖特定的错误消息:

$myMessages = [
   'notSame' => 'The Entered Password is not Correct'
];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM