def __call__(self, fn): @implementer(IValidator) def factory(context, request, view, field, widget): return DecoratedValidator(fn, context, request, view, field, widget) WidgetValidatorDiscriminators(factory, **self.discriminators) frame = sys._getframe(1) adapters = frame.f_locals.get('__form_validator_adapters__', None) if adapters is None: frame.f_locals['__form_validator_adapters__'] = adapters = [] adapters.append(factory) return fn
description=_(u'help_allowed_proposal_templates', default=u'Select the proposal templates allowed for' u' this commitee, or select no templates for allowing' u' all templates.'), value_type=schema.Choice( source='opengever.meeting.ProposalTemplatesVocabulary'), required=False, default=None, missing_value=None) class RepositoryfolderValidator(BaseRepositoryfolderValidator): pass WidgetValidatorDiscriminators(RepositoryfolderValidator, field=ICommittee['repository_folder']) class ICommitteeModel(Interface): """Proposal model schema interface.""" title = schema.TextLine( title=_(u"label_title", default=u"Title"), required=True, max_length=256, ) group_id = schema.Choice( title=_('label_committee_responsible', default="Committeeresponsible"), description=_( u'description_group',
if re.match(r'^https?://', value): return raise Invalid( _(u'destination_must_be_path_or_url', default=u'Row ${rownum}: the destination "${value}"' u' must be a path (start with slash)' u' or a full qualified URL.', mapping={ 'rownum': rownum, 'value': value })) WidgetValidatorDiscriminators(RulesValidator, field=IRedirectConfigSchema['rules']) class RedirectConfig(Item): implements(IRedirectConfig) def Title(self): return _(u'Redirect Configuration') @property def exclude_from_nav(self): return True def cb_isMoveable(self): return 0
@implementer(IFieldWidget) @adapter(INamedFileField, IRedirectorLayer) def ForceFileUploadFieldWidget(field, request): return FieldWidget(field, ForceFileUploadWidget(request)) class IRulesUploadSchema(form.Schema): form.primary('rules_file') rules_file = NamedBlobFile( title=_(u'redirect_config_file', default=u'Excel redirect config'), required=True) WidgetValidatorDiscriminators(RedirectConfigExcelValidator, field=IRulesUploadSchema['rules_file']) provideAdapter(RedirectConfigExcelValidator) class ImportRedirectConfigView(form.SchemaForm): schema = IRulesUploadSchema ignoreContext = True label = _(u"Upload redirect config") def updateWidgets(self): # use the basic widget to disable "keep existing file" self.fields['rules_file'].widgetFactory = ForceFileUploadFieldWidget super(ImportRedirectConfigView, self).updateWidgets()
from Products.CMFCore.utils import getToolByName from collective.behavior.sku import _ from collective.behavior.sku.interfaces import ISKU from z3c.form.validator import SimpleFieldValidator from z3c.form.validator import WidgetValidatorDiscriminators from zope.interface import Invalid class ValidateSKUUniqueness(SimpleFieldValidator): """Validate uniqueness of SKU.""" def validate(self, value): super(ValidateSKUUniqueness, self).validate(value) if getattr(self.context, 'sku', u'') != value: catalog = getToolByName(self.context, 'portal_catalog') brains = catalog({ 'sku': value, }) if brains: raise Invalid(_(u'The SKU is already in use.')) WidgetValidatorDiscriminators(ValidateSKUUniqueness, field=ISKU['sku'])
def container(self): return self.context class FlourishOverlapEditValidator(FlourishOverlapValidator): @property def schoolyear(self): return self.context @property def container(self): return self.context.__parent__ WidgetValidatorDiscriminators(FlourishOverlapAddValidator, view=FlourishSchoolYearAddView, field=ISchoolYearAddForm['first']) WidgetValidatorDiscriminators(FlourishOverlapEditValidator, view=FlourishSchoolYearEditView, field=ISchoolYearAddForm['first']) class OverlapErrorViewSnippet(ErrorViewSnippet): adapts(SchoolYearOverlapError, None, None, None, None, None) render = ViewPageTemplateFile("templates/school_year_overlap_error.pt") def schoolyears(self): return self.context.overlapping_schoolyears
'IRepositoryFolderSchema', navigation_tree_query={ 'object_provides': [ 'opengever.repository.repositoryroot.IRepositoryRoot', 'opengever.repository.repositoryfolder.' 'IRepositoryFolderSchema', ] })) class RepositoryfolderValidator(BaseRepositoryfolderValidator): pass WidgetValidatorDiscriminators( RepositoryfolderValidator, field=ISelectRepositoryfolderSchema['repositoryfolder']) grok.global_adapter(RepositoryfolderValidator) class SelectRepositoryfolderStepForm(AcceptWizardNewDossierFormMixin, Form): fields = Fields(ISelectRepositoryfolderSchema) step_name = 'accept_select_repositoryfolder' @buttonAndHandler(_(u'button_continue', default=u'Continue'), name='save') def handle_continue(self, action): data, errors = self.extractData() if not errors: folder = data['repositoryfolder']
super(DossierValidator, self).validate(value) document_addable = False for fti in value.allowedContentTypes(): if fti.id == 'opengever.document.document': document_addable = True break if not document_addable: msg = _(u'You cannot add documents to the selected dossier. ' u'Either the dossier is closed or you do not have the ' u'privileges.') raise Invalid(msg) WidgetValidatorDiscriminators(DossierValidator, field=IChooseDossierSchema['dossier']) grok.global_adapter(DossierValidator) class ChooseDossierStepForm(CloseTaskWizardStepFormMixin, Form): fields = Fields(IChooseDossierSchema) step_name = 'close-task-wizard_choose-dossier' @buttonAndHandler(_(u'button_save', default=u'Save'), name='save') def handle_save(self, action): data, errors = self.extractData() if not errors: query = getUtility(ITaskQuery) info = getUtility(IContactInformation) dm = getUtility(IWizardDataStorage)
def validate(self, value): super(TermBoundsValidator, self).validate(value) if ISchoolYear.providedBy(self.view.context): sy = self.view.context else: sy = self.view.context.__parent__ if value not in IDateRange(sy): raise DateOutOfYearBounds(self.view.context, value) class FirstTermBoundsValidator(TermBoundsValidator): pass WidgetValidatorDiscriminators( FirstTermBoundsValidator, field=ITermForm['first']) class LastTermBoundsValidator(TermBoundsValidator): pass WidgetValidatorDiscriminators( LastTermBoundsValidator, field=ITermForm['last']) class FlourishInvalidDateRangeError(ValidationError): __doc__ = _('Term must begin before it ends.')
def validate(self, value): super(MethodValidator, self).validate(value) if value != u'participate': org_unit = self.context.get_responsible_org_unit() if org_unit not in ogds_service().assigned_org_units(): msg = _(u'You are not assigned to the responsible client ' u'(${client}). You can only process the task in the ' u'issuers dossier.', mapping={'client': org_unit.id()}) raise Invalid(msg) WidgetValidatorDiscriminators(MethodValidator, field=IChooseMethodSchema['method']) class ChooseMethodStepForm(AcceptWizardFormMixin, Form): fields = Fields(IChooseMethodSchema) fields['method'].widgetFactory[INPUT_MODE] = RadioFieldWidget step_name = 'accept_choose_method' @property def label(self): if self.context.task_type == 'forwarding_task_type': _(u'title_accept_forwarding', u'Accept forwarding') return _(u'title_accept_task', u'Accept task')
primary('file') file = NamedBlobFile(title=_(u'label_file', default='File'), required=True) class UploadValidator(SimpleFieldValidator): allowed_extensions = ('.docx', ) def validate(self, value): """The uploaded file in a proposal template must be a .docx so that we can process it later. """ if value and value.filename: basename, extension = os.path.splitext(value.filename) if extension.lower() in self.allowed_extensions: return raise Invalid( _(u'error_prosal_template_not_docx', default=u'Only word files (.docx) can be added here.')) WidgetValidatorDiscriminators(UploadValidator, field=IProposalTemplate['file']) class ProposalTemplate(Document): """Proposal templates are added to the template folder. They have a word-file attached, which is copied when creating a new proposal. """
def __call__(self, cls): if 'schema' in self.kw: WidgetsValidatorDiscriminators(cls, **self.kw) else: WidgetValidatorDiscriminators(cls, **self.kw) return cls
MAIL_EXPRESSION = r"^(\w&.%#$&'\*+-/=?^_`{}|~]+!)*[\w&.%#$&'\*+-/=" +\ "?^_`{}|~]+@(([0-9a-z]([0-9a-z-]*[0-9a-z])?" +\ "\.)+[a-z]{2,6}|([0-9]{1,3}\.){3}[0-9]{1,3})$" def __init__(self, *args, **kwargs): super(AddressesValidator, self).__init__(*args, **kwargs) self.email_expression = re.compile(AddressesValidator.MAIL_EXPRESSION, re.IGNORECASE) def validate(self, value): """Validates the `value`, expects a list of carriage-return-separated email addresses. """ super(AddressesValidator, self).validate(value) if value: address = value.strip() self._validate_addresses(address) def _validate_addresses(self, address): """E-Mail address validation """ address = address.strip() if not self.email_expression.match(address): msg = _(u'error_invalid_addresses', default=u'Your E-mail address is not valid.') raise Invalid(msg) WidgetValidatorDiscriminators(AddressesValidator, field=IContactForm['email']) provideAdapter(AddressesValidator)