Using a Form Widget Validator on multiple fields

277 Views Asked by At

I've written a custom validator for my schema field as shown in the documentation here: http://docs.plone.org/develop/plone/forms/z3c.form.html#form-widget-validators

enter image description here

My question is that if i want to use the same validator for a few different fields, is that possible? It doesnt seem to work. eg I would like to write:

# Set conditions for which fields the validator class applies
validator.WidgetValidatorDiscriminators(PhoneNumberValidator, field=IZohoContactForm['phone_number'])
validator.WidgetValidatorDiscriminators(PhoneNumberValidator, field=IZohoContactForm['another_phone_field'])
3

There are 3 best solutions below

0
On BEST ANSWER

As a workaround I have written two identical validators with different names which violates the DRY principle but not much i can for this one it seems...

0
On

It's an old question but I just recently faced this problem and this is my approach:

  1. Set a schema interface for the field to be validated.
class ICaptchaSchema(model.Schema):
    captcha = schema.TextLine(
            title=_('security_check', default="Security check"),
        )
  1. Use the field in form schema interface:
class IFormSchema(model.Schema):
    captcha1 = ICaptchaSchema['captcha']
    captcha2 = ICaptchaSchema['captcha']

  1. Register form widget validator for the first schema iterface:
validator.WidgetValidatorDiscriminators(YourCustomValidator,
                                        field=ICaptchaSchema['captcha'])

All fields "captcha" will be adapted.

Regards.

1
On

It is possible to pass a field type as well for the field argument (see: https://docs.plone.org/develop/addons/schema-driven-forms/customising-form-behaviour/validation.html#field-widget-validators): validator.WidgetValidatorDiscriminators(MyListValidator, field=schema.List)

In the above example the validator is applied to all fields of type schema.List