[英]Plone: Validate field based on other field's value
Let's say we have a dexterity content type with two fields: field_a
and field_b
. 假设我们有一个敏捷性内容类型,其中包含两个字段:
field_a
和field_b
。
In edit mode: 在编辑模式下:
field_a
has the category_1
value selected then field_b
is not required field_a
选择了category_1
值,则field_b
field_b
has other value selected then field_b
is required field_b
选择了其他值,则需要field_b
It seems a simple validation is not possible here. 在这里似乎无法进行简单的验证。 I tried:
我试过了:
from zope.interface import Invalid
def validate_field_b(value):
# value is a string here. I can't create a condition based on field_a.
raise Invalid(_(u"Value in field b is required."))
used here: 在这里使用:
field_b = schema.TextLine(
title=_(u"Some field B"),
required=False,
constraint=validate_field_b
)
The result is field_b
required all the time. 结果始终是
field_b
。 :) :)
Any solution here? 有什么解决办法吗? How the get the form / context / request / other fields value in my validator?
如何在验证器中获取表单/上下文/请求/其他字段的值?
The solution is to use an invariant
instead of constraint
: https://docs.plone.org/external/plone.app.dexterity/docs/advanced/validators.html#invariants 解决方案是使用
invariant
而不是constraint
: https : //docs.plone.org/external/plone.app.dexterity/docs/advanced/validators.html#invariants
@invariant
def validate_field_b(data):
if data.field_a != 'category_1' and data.field_b is None:
raise Invalid(_("Missing input for field_b."))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.