zopefoundation / z3c.form

An advanced form and widget framework for Zope 3
Other
8 stars 39 forks source link

Using a validator on multiple fields #61

Open cdw9 opened 7 years ago

cdw9 commented 7 years ago

I've created a validator, but it will only work on one field at a time. Currently I have:

validator.WidgetValidatorDiscriminators(
    AlphaNumericValidator, field=ITracker['available_areas'])
validator.WidgetValidatorDiscriminators(
    AlphaNumericValidator, field=ITracker['available_issue_types'])
validator.WidgetValidatorDiscriminators(
    AlphaNumericValidator, field=ITracker['available_severities'])

The validator will work on one of the fields, but ignores the other two. I've confirmed the validation works on each separately. How can I use the same validator on multiple fields?

cdw9 commented 7 years ago

Also the docs indicate I can specify a widget instead of a field. Two of these fields use the same widget, so I tried:

validator.WidgetValidatorDiscriminators(
    AlphaNumericValidator, widget=DataGridFieldFactory)

But this did not work either, and there is no error. The validator is not accessed.

Netroxen commented 7 years ago

Would also like some feedback on this, would be nice to pass multiple fields to the validator..?

icemac commented 7 years ago

I believe you have to use different discriminators to get this working. @cdw9 Is it correct that each of your fields uses the same zope.schema field class? If yes it results in the same discriminator. (Maybe an exception should be raised if this happens but this can be filed as in issue if my analysis is correct here.)

A workaround could be to provide a special interface for each field. Like this: (untested)


class IAvailableAreas(zope.interface.Interface):
    pass

class IAvailableIssueTypes(zope.interface.Interface):
    pass

class ITracker(zope.interface.Interface):
    available_areas = zope.schema.TextLine()
    available_issue_types = zope.schema.TextLine()

zope.interface.alsoProvides(ITracker['available_areas'], IAvailableAreas)
zope.interface.alsoProvides(ITracker['available_issue_types'], IAlphaNumValue2)

validator.WidgetValidatorDiscriminators(
    AlphaNumericValidator, field=IAvailableAreas)
validator.WidgetValidatorDiscriminators(
    AlphaNumericValidator, field=IAvailableIssueTypes)

Does this help?