zend-framework - Laminas / ZF3:手动将错误添加到字段
问题描述
是否可以在字段验证和输入过滤器之后手动向字段添加错误消息?
如果用户名和密码错误,我需要它来标记这些字段/显示错误消息。
显然在 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 的文档,你会发现很多有用的信息
推荐阅读
- meteor - SendGrid sgMail.send 使用咖啡脚本流星的错误。作为纯 JS 工作正常
- php - 将 id 传递给 URL 时如何发布 the_content
- javascript - JavaScript 中的对象字面量问题
- c# - MVC 控制器中的 List____() 应该对用户返回什么未经授权?
- database - 为什么 XY 不是候选键?
- baseline - OSquery - 如何预加载数据以查找受感染的文件
- android - 检测位置设置何时可用(例如:记录其使用时间等)?
- vue.js - 在 vue.js 中添加插件失败
- javascript - 尝试制作动态填充的链接选择框以在页面上显示特定图像
- ubuntu - 程序图标在任务栏上显示两次。它不是双重安装的。我怎么能只有一个?