元素标签作为错误消息中的变量进行验证
是否可以在错误消息中使用引用表单元素标签的变量?可以映射自定义变量,例如 %hostname% (在电子邮件验证器中),并且 %value% 也可用,但我也希望拥有表单标签。
我在 ZF 代码库中找不到它,但用例是 Zend_Validate_NotEmpty 可以返回如下消息:
"The field %label% is required and can't be empty"
而不是:
"Value is required and can't be empty"
Is it possible to use a variable inside the error message referring to the label of the form element? It's possible to map custom variables like %hostname% (in email validator) and the %value% is also available, but I'd like to have the form label as well.
I could't find it in the ZF codebase, but the use case is for example that the Zend_Validate_NotEmpty can return a message like:
"The field %label% is required and can't be empty"
Instead of:
"Value is required and can't be empty"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为如果不对验证器进行子类化是不可能的。
Zend_Validate
类不仅仅与Zend_Form_Element
一起使用。消息中包含%label%
会在两个组件之间引入耦合。一个可能的解决方案是通过扩展 Zend_Validate_NotEmpty(或您正在使用的任何验证器)来创建自定义验证器,并将标签传递给构造函数。这样,您可以在每次实例化它时编写适当的消息。
编辑:
如果您遵循上面的方法,您甚至可以定义自己的
%label%
“魔术变量”并将其附加到类的成员。请参阅 Zend Framework 文档中示例 #2 中的$_messageVariables
成员: 编写验证器希望有帮助...
I think it's not possible without subclassing the validators. The
Zend_Validate
classes are not intended to be used withZend_Form_Element
only. Having a%label%
in the message would introduce a coupling between both components.A possible solution could be to create custom validators by extending
Zend_Validate_NotEmpty
(or whatever validators you are using) and pass the label to the constructor. This way, you could compose the appropriate message every time you instantiate it.EDIT:
If you follow the method above, you could even define your own
%label%
"magic variable" and attach it to a member of the class. See the$_messageVariables
member in the Example #2 in the Zend Framework documentation: Writing validatorsHope that helps...
我最后还是和装修师一起去了。 dinopmi 的解决方案是可能的,但是您需要始终注入标签。我的表单元素错误装饰器现在将 %label% 替换为真实标签。
I finally went with the decorator. The solution of dinopmi is possible, however you need to inject the label all the times. My error decorator for the form element replaces now the %label% to the real label.