元素标签作为错误消息中的变量进行验证

发布于 2024-12-03 03:22:12 字数 311 浏览 0 评论 0原文

是否可以在错误消息中使用引用表单元素标签的变量?可以映射自定义变量,例如 %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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巡山小妖精 2024-12-10 03:22:12

我认为如果不对验证器进行子类化是不可能的。 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 with Zend_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 validators

Hope that helps...

海螺姑娘 2024-12-10 03:22:12

我最后还是和装修师一起去了。 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文