简体   繁体   中英

Using a Form Widget Validator on multiple fields

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

在此处输入图片说明

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'])

作为一种解决方法,我编写了两个具有不同名称的相同验证器,这违反了 DRY 原则,但我对此似乎无能为力……

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM