是否可以在字段验证和输入过滤器之后手动向字段添加错误消息?
如果用户名和密码错误,我需要它来标记这些字段/显示错误消息。
显然在 ZF/ZF2 中可以使用$form->getElement('password')->addErrorMessage('The Entered Password is not Correct');
- 但这在 ZF3/Laminas 中不再起作用
是否可以在字段验证和输入过滤器之后手动向字段添加错误消息?
如果用户名和密码错误,我需要它来标记这些字段/显示错误消息。
显然在 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 的文档,你会发现很多有用的信息