我有一个用于捕获电子邮件地址的表单元素。我在元素上使用 Zend_Validate_EmailAddress
,它生成的错误消息对用户来说不是很友好。
我的第一步是指定对用户更友好的新消息,但有些检查根本不适合用户友好的消息。然后我尝试在表单上运行 isValid()
并指定我自己的后简单地清除这些消息,但我发现的函数都不会清除消息。
我的尝试和结果
setErrorMessages()
- 此处设置的值似乎完全被忽略了clearErrorMessages()
- 似乎被忽略了setErrors()
- 添加我的信息,但保留其他信息不变
这是在我的自定义 View 脚本中显示错误的代码:
<?php if ($this->element->hasErrors()): ?>
<?php echo $this->formErrors($this->element->getMessages()); ?>
<?php endif; ?>
我的解决方案
我正在授予 Gordon有了答案,因为他的解决方案是最完整的,但我最终在元素 like this 上使用了 addErrorMessage()
函数:
$element->addValidator('EmailAddress', false, $this->_validate['EmailAddress'])
->addErrorMessage("'%value%' is not a valid email address");
$element->addValidator('Date', false, array('MM/dd/yyyy'))
->addErrorMessage("Date must be in MM/DD/YYYY format");
最佳答案
来自引用指南(强调我的):
Some developers may wish to provide custom error messages for a validator. The
$options
argument of theZend_Form_Element::addValidator()
method allows you to do so by providing the key'messages'
and mapping it to an array of key/value pairs for setting the message templates. You will need to know the error codes of the various validation error types for the particular validator.
所以你可以这样做:
$form = new Zend_Form;
$username = new Zend_Form_Element_Text('username');
$username->addValidator('regex', false, array(
'/^[a-z]/i',
'messages' => array(
'regexInvalid' => 'foo',
'regexNotMatch' => 'bar',
'regexErrorous' => 'baz'
)
));
$form->addElement($username);
$form->isValid(array('username' => '!foo'));
然后将为错误消息呈现“bar”,因为正则表达式不匹配,因为它不是以 a-Z 中的字母开头。
这相当于使用:
$username->setErrorMessages(
array(
'regexNotMatch' => 'The value %value% must start with a-Z',
…
)
);
我使用了不同的模式来说明如何在模式中使用经过验证的值。
如果你想删除任何默认模板,你也可以使用setErrors
,例如
$username->setErrors(array('The value must start with a-Z'));
无论您做什么,都必须在之前使用isValid
进行验证。一旦运行验证,Zend_Form_Element
将否则包含默认错误消息。我不知道有什么方法可以重置它(尽管有人可能想纠正我)。
进一步引用引用指南:
A better option is to use a Zend_Translate_Adapter with your form. Error codes are automatically passed to the adapter by the default Errors decorator; you can then specify your own error message strings by setting up translations for the various error codes of your validators.
所有验证消息都可以从
中的文件中自定义该文件应该在 APPLICATION_PATH/resources/languages
中,但实际上可以放在任何地方,只要您告诉 Zend_Translate
在哪里可以找到它。
关于php - 从 Zend 表单元素中清除验证错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5734376/