plonedexterityplone-4.x

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.

In edit mode:

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. :)

Any solution here? How the get the form / context / request / other fields value in my validator?


Solution

  • The solution is to use an invariant instead of 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."))