我在这个答案中使用了验证器错误自定义示例:https://stackoverflow.com/a/4881030/822947,但我需要使用addValidator()或setMessage()/ setMessages()来覆盖一些已翻译的错误。下面的例子不起作用(看起来,内置翻译有优先权吗?)......我怎么能这样做?
$field->addValidator ('Alpha', false, array ('messages' => array (Zend_Validate_Alpha::NOT_ALPHA => 'My msg')));
$Alpha = new Zend_Validate_Alpha ();
$Alpha->setDisableTranslator (true);
$Alpha->setMessage ('My msg', Zend_Validate_Alpha::NOT_ALPHA);
$Alpha->setMessages (array (Zend_Validate_Alpha::NOT_ALPHA => 'My msg'));
$field->addValidator ($Alpha);
更新 问题不在于我添加验证器和设置消息的方式。
我的目标是本地化所有错误消息。但是对于一些表单字段,我需要添加更多特定的消息。
例如,在我的lang / translate.php中,我有共同点
Zend_Validate_Alpha::NOT_ALPHA => 'Value contains non alphabetic characters'
,
但是对于名字字段,我需要更具体
Zend_Validate_Alpha::NOT_ALPHA => 'Field can contain only alphabetic characters and spaces'
,
当我启用内置翻译器时,问题是忽略了特定的消息。所以例如代码
$form = new Zend_Form ();
$validator = new Zend_Validate_Alpha ();
$validator->setMessages (array (
Zend_Validate_Alpha::NOT_ALPHA => 'xxx %value% x'
));
$form->addElement ('text', 'digit', array (
'validators' => array (
$validator
)
));
$name = new Zend_Form_Element_Text ('name');
$name->addValidator ('Alpha', true, array (
'allowWhiteSpace' => true,
'messages' => array
(
Zend_Validate_Alpha::NOT_ALPHA => 'my more specific localized msg',
)
));
$form->addElement ($name);
$form->isValid (array (
'digit' => '___',
'name' => '___',
));
Zend_Debug::dump ($form->getMessages ());
当译员禁用时,我有
array(2) {
'digit' =>
array(1) {
'notAlpha' =>
string(9) "xxx ___ x"
}
'name' =>
array(1) {
'notAlpha' =>
string(30) "my more specific localized msg"
}
}
启用翻译后,我收到来自lang / translate.php的消息
array(2) {
'digit' =>
array(1) {
'notAlpha' =>
string(104) "common localized msg"
}
'name' =>
array(1) {
'notAlpha' =>
string(104) "common localized msg"
}
}
答案 0 :(得分:2)
问题是Alpha验证器不支持构造函数的参数中的选项数组。你必须单独设置它们。
$form = new Zend_Form ();
$validator = new Zend_Validate_Alpha ();
/* Custom error message */
$validator->setMessages (array (
Zend_Validate_Alpha::NOT_ALPHA => 'xxx %value% x'
));
$form->addElement ('text', 'digit', array (
'validators' => array (
$validator
)
));
$form->isValid (array (
'digit' => '___'
));
Zend_Debug::dump ($form->getMessages ());
问题在于你的翻译。
我的翻译器配置如下:
resources.translate.adapter = Array
resources.translate.data = APPLICATION_PATH "/test-translate"
file en.php:
return array (
"notAlpha" => 'my Translated alpha'
);
它有效。