comments = schema.Text( title=_(u'label_comments', default=u'Comments'), required=False) class EmailAddressValidator(SimpleFieldValidator): def validate(self, value): super(EmailAddressValidator, self).validate(value) if not value or not is_email_valid(value): raise Invalid(_(u'This email address is invalid.')) validator.WidgetValidatorDiscriminators( EmailAddressValidator, field=IDefaultContactInformation['email']) class IShippingAddress(Interface): """Schema defining a form for entering a shipping address """ used = schema.Bool( title=_(u'label_used', default=u'Different from invoice address'), default=False, required=False) class IStatusSet(Interface): """Interface defining a set of statuses that an order can be in.
from z3c.form import validator from zope.schema import ValidationError from plone.namedfile.interfaces import INamedField from plone.formwidget.namedfile import MessageFactory as _ class InvalidState(ValidationError): __doc__ = _(u'No file provided.') class NamedFileWidgetValidator(validator.SimpleFieldValidator): def validate(self, value): """See interfaces.IValidator""" action = self.request.get("%s.action" % self.widget.name, None) if action == 'replace' and value is None: raise InvalidState() return super(NamedFileWidgetValidator, self).validate(value) validator.WidgetValidatorDiscriminators(NamedFileWidgetValidator, field=INamedField)
def validate(self, value): super(DestinationValidator, self).validate(value) # Allowed contenttypes for destination-folder allowed_types = [t.getId() for t in value.allowedContentTypes()] # Paths to source object source = self.view.widgets['request_paths'].value.split(';;') # Get source-brains portal_catalog = getToolByName(self.context, 'portal_catalog') src_brains = portal_catalog(path={'query': source, 'depth': 0}) failed_objects = [] # Look for invalid contenttype for src_brain in src_brains: if src_brain.portal_type not in allowed_types: failed_objects.append(src_brain.Title.decode('utf8')) # If we found one or more invalid contenttypes, we raise an error if failed_objects: raise NotInContentTypes( _(u"error_NotInContentTypes ${failed_objects}", default=u"It isn't allowed to add such items there: " "${failed_objects}", mapping=dict(failed_objects=', '.join(failed_objects)))) validator.WidgetValidatorDiscriminators( DestinationValidator, field=IMoveItemsSchema['destination_folder'])
z3c.form validator class for checking title uniqueness. """ def validate(self, value): """ Validate titles. """ super(TitleValidator, self).validate(value) context_portal_type = self.context.Type() if context_portal_type == 'Contacts': results = api.content.find(portal_type='Contact', Title=value) # noqa if results: raise zope.interface.Invalid( _(u'contact_title_form_validator_message', default=u'Display Name not unique!')) else: return True else: return True validator.WidgetValidatorDiscriminators(TitleValidator, field=IContact['title']) # noqa zope.component.provideAdapter(TitleValidator) class Contact(Item): """ Contact class """
super(ValidateEUpProjectUniqueness, self).validate(value) if value is not None: catalog = api.portal.get_tool(name='portal_catalog') results = catalog({ 'Title': quote_chars(value), 'object_provides': IEUpProject.__identifier__ }) contextUUID = IUUID(self.context, None) for result in results: if result.UID != contextUUID: raise Invalid(_(u"The project title is already in use.")) validator.WidgetValidatorDiscriminators( ValidateEUpProjectUniqueness, field=IEUpProject['title'], ) class EUpProjectView(DefaultView): def all_releases(self): """Get a list of all releases, ordered by version, starting with the latest. """ catalog = api.portal.get_tool(name='portal_catalog') current_path = "/".join(self.context.getPhysicalPath()) res = catalog.searchResults( portal_type=('tdf.extensionuploadcenter.euprelease', 'tdf.extensionuploadcenter.eupreleaselink'), path=current_path, sort_on='Date',
class CaptchaValidator(validator.SimpleFieldValidator): implements(IValidator) adapts(Interface, IDiscussionLayer, Interface, IField, Interface) # Object, Request, Form, Field, Widget, # We adapt the CaptchaValidator class to all form fields (IField) def validate(self, value): super(CaptchaValidator, self).validate(value) registry = queryUtility(IRegistry) settings = registry.forInterface(IDiscussionSettings, check=False) if settings.captcha in ('captcha', 'recaptcha', 'norobots'): captcha = getMultiAdapter((aq_inner(self.context), self.request), name=settings.captcha) if not captcha.verify(input=value): if settings.captcha == 'norobots': raise WrongNorobotsAnswer else: raise WrongCaptchaCode else: return True # Register Captcha validator for the Captcha field in the ICaptcha Form validator.WidgetValidatorDiscriminators(CaptchaValidator, field=ICaptcha['captcha'])
_('reference_validation_image', u'You can only select images.')) class LinksValidator(validator.SimpleFieldValidator): """z3c.form validator class for related images """ def validate(self, value): """Validate links """ super(LinksValidator, self).validate(value) if not value: return invalids = filter(lambda x: x.portal_type != 'Link', value) if invalids: raise Invalid( _('reference_validation_link', u'You can only select Links.')) # Set conditions for which fields the validator class applies validator.WidgetValidatorDiscriminators(ImageValidator, field=IRERNews['image']) validator.WidgetValidatorDiscriminators(LinksValidator, field=IRERNews['related_links']) # Register the validator so it will be looked up by z3c.form machinery # this should be done via ZCML provideAdapter(ImageValidator) provideAdapter(LinksValidator)
def is_save_pdf_under_available(self): return IBumblebeeServiceV3(self.request).is_convertable(self.context) class NotInContentTypes(Invalid): __doc__ = _(u"error_NotInContentTypes", default=u"User is not allowed to add a document there.") class DestinationValidator(validator.SimpleFieldValidator): """Validator for destination-path. We check that the source-typ is allowed in the destination. We also check that the user has the required permissions to add content in the destination object. """ def validate(self, value): super(DestinationValidator, self).validate(value) # Allowed contenttypes for destination-folder allowed_types = [t.getId() for t in value.allowedContentTypes()] if self.context.portal_type not in allowed_types: raise NotInContentTypes( _(u"error_NotInContentTypes", default=u"User is not allowed to add a document there.")) validator.WidgetValidatorDiscriminators( DestinationValidator, field=ISaveAsPdfSchema['destination_folder'])
item_count = schema.Int(title=_(u'# of items'), ) class TypeIdValidator(validator.SimpleFieldValidator): def validate(self, value): super(TypeIdValidator, self).validate(value) ttool = getToolByName(self.context, 'portal_types') if value in ttool.objectIds(): raise Invalid( _(u"There is already a content type named '${name}'", mapping={'name': value})) validator.WidgetValidatorDiscriminators(TypeIdValidator, field=ITypeSettings['id']) class TypeTitleValidator(validator.SimpleFieldValidator): def validate(self, value): super(TypeTitleValidator, self).validate(value) ttool = getToolByName(self.context, 'portal_types') for existing_fti in ttool.objectValues(): if aq_base(existing_fti) is aq_base(self.context): continue if existing_fti.Title() == value: raise Invalid( _(u"There is already a content type named '${name}'", mapping={'name': value}))
self.widgets['origtitle'].required = True class OrigDateRequiredValidator(validator.SimpleFieldValidator): """ In the beispiel application we always want the 'origdate' field present.""" def validate(self, value): super(OrigDateRequiredValidator, self).validate(value) if not value: raise zope.interface.Invalid( _(u"No value for 'origdate' provided.")) validator.WidgetValidatorDiscriminators( OrigDateRequiredValidator, field=IBiblatexEntry['origdate'], request=IBeispielBrowserLayer, ) class OrigTitleRequiredValidator(validator.SimpleFieldValidator): """ In the beispiel application we always want the 'origtitle' field present.""" def validate(self, value): super(OrigTitleRequiredValidator, self).validate(value) if not value: raise zope.interface.Invalid( _(u"No value for 'origtitle' provided.")) validator.WidgetValidatorDiscriminators(
) colorize_project_rows = schema.Bool( title=_(u"colorize project's rows"), description=_(u"Visual way to highlight internal panes in dashboards"), default=False, ) @invariant def validateSettings(data): mandatory_check(data, field_constraints) position_check(data, field_constraints) validator.WidgetValidatorDiscriminators( RemovedValueIsNotUsedByCategoriesFieldValidator, field=IProjectSpace['categories_values']) provideAdapter(RemovedValueIsNotUsedByCategoriesFieldValidator) validator.WidgetValidatorDiscriminators( RemovedValueIsNotUsedByPriorityFieldValidator, field=IProjectSpace['priority_values']) provideAdapter(RemovedValueIsNotUsedByPriorityFieldValidator) validator.WidgetValidatorDiscriminators( RemovedValueIsNotUsedByBudgetTypesFieldValidator, field=IProjectSpace['budget_types']) provideAdapter(RemovedValueIsNotUsedByBudgetTypesFieldValidator) class ProjectSpace(Container):
def validate_pod_file(data): if not (data.odt_file or data.pod_template_to_use): raise Invalid( _("You must select an odt file or an existing pod template"), schema) @invariant def validate_pod_template_to_use(data): if data.pod_template_to_use and (data.is_reusable or data.odt_file): raise Invalid( _("You can't select a POD Template or set this template reusable " "if you have chosen an existing POD Template."), schema) # Set conditions for which fields the validator class applies validator.WidgetValidatorDiscriminators( PodFormatsValidator, field=IConfigurablePODTemplate['pod_formats']) # Register the validator so it will be looked up by z3c.form machinery provideAdapter(PodFormatsValidator) @implementer(IConfigurablePODTemplate) class ConfigurablePODTemplate(PODTemplate): """ ConfigurablePODTemplate dexterity class. """ parent_pod_annotation_key = 'linked_child_templates' def get_pod_template_to_use(self): """
""" """ def validate(self, value): """ """ super(EndValidator, self).validate(value) room_end = self.context.ende.split(':') room_time_end = datetime.time(int(room_end[0]), int(room_end[1])) if value.time() > room_time_end: raise Invalid( _(u'Dad Ende der Veranstaltung darf nicht nach Schließung des Raumes liegen.' )) adressen = validator.WidgetValidatorDiscriminators( AdressenValidator, field=IVeranstaltung['adressen']) start = validator.WidgetValidatorDiscriminators(StartValidator, field=IVeranstaltung['start']) end = validator.WidgetValidatorDiscriminators(EndValidator, field=IVeranstaltung['end']) zope.component.provideAdapter(AdressenValidator) zope.component.provideAdapter(StartValidator) zope.component.provideAdapter(EndValidator) @implementer(IVeranstaltung) class Veranstaltung(Container): """
'portal_type': [ 'tdf.extensionuploadcenter.euprelease', 'tdf.extensionuploadcenter.eupreleaselink' ], 'release_number': value }) if len(result) > 0: raise Invalid( _(u"The release number is already in use. Please choose another one." )) validator.WidgetValidatorDiscriminators( ValidateEUpReleaseLinkUniqueness, field=IEUpReleaseLink['releasenumber'], ) class EUpReleaseLinkView(DefaultView): def canPublishContent(self): return checkPermission('cmf.ModifyPortalContent', self.context) def releaseLicense(self): catalog = api.portal.get_tool(name='portal_catalog') path = "/".join(self.context.getPhysicalPath()) idx_data = catalog.getIndexDataForUID(path) licenses = idx_data.get('releaseLicense') return (r for r in licenses) def linkedreleaseCompatibility(self):
raise Invalid(_(u'error_private_task_feature_is_disabled', default=u'The private task feature is disabled')) @invariant def revoke_permissions_is_not_changed_when_disabled(data): if not is_optional_task_permissions_revoking_enabled(): # Because the z3c.form.validator.Data object has implemented a # getattr fallback, which fetches the value from the context, we # need to check if the revoke_permissions value was part of the input-data. if 'revoke_permissions' in data._Data_data___ and not data.revoke_permissions: raise Invalid(_(u'error_revoke_permissions_feature_is_disabled', default=u'The revoke permissions feature is disabled')) validator.WidgetValidatorDiscriminators( NoCheckedoutDocsValidator, field=ITask['relatedItems'], ) default_responsible_client = widget.ComputedWidgetAttribute( lambda adapter: get_current_org_unit().id(), field=ITask['responsible_client'], ) class IAddTaskSchema(ITask): """Define a schema for adding tasks.""" form.widget('responsible', KeywordFieldWidget, async=True) model.fieldset( u'additional',
class WorkGroupIdValidator(validator.SimpleFieldValidator): """Two users can't have the same username.""" def validate(self, value, force=False): membrane_tool = plone_api.portal.get_tool('membrane_tool') groupids = membrane_tool._catalog.uniqueValuesFor('exact_getGroupId') if value in groupids: brains = membrane_tool.searchResults(exact_getGroupId=value) if brains and self.context != brains[0].getObject(): raise Invalid(_("A group with this id already exists")) return super(WorkGroupIdValidator, self).validate(value) validator.WidgetValidatorDiscriminators(WorkGroupIdValidator, field=IWorkGroup['id']) class WorkGroupGroupsProvider(object): """ Determine the groups to which a principal belongs. A principal can be a user or a group. See the docstring of ploneintranet.workspace.behaviors.groups.MembraneWorkspaceGroupsProvider for in depth information on the call flow. """ security = ClassSecurityInfo()
class ReferenceNumberPrefixValidator(validator.SimpleFieldValidator): def validate(self, value): # setting parent, for that we check if there are a Add- or a Editform super(ReferenceNumberPrefixValidator, self).validate(value) if IAddForm.providedBy(self.view.parentForm): if not PrefixAdapter(self.context).is_valid_number(value): raise schema.interfaces.ConstraintNotSatisfied() else: parent = aq_parent(aq_inner(self.context)) if not PrefixAdapter(parent).is_valid_number(value, self.context): raise schema.interfaces.ConstraintNotSatisfied() validator.WidgetValidatorDiscriminators( ReferenceNumberPrefixValidator, field=IReferenceNumberPrefix['reference_number_prefix'], ) provideAdapter(ReferenceNumberPrefixValidator) provideAdapter(error.ErrorViewMessage( _('error_sibling_reference_number_existing', default=u'A Sibling with the same reference number is existing'), error=schema.interfaces.ConstraintNotSatisfied, field=IReferenceNumberPrefix['reference_number_prefix'], ), name='message') class IReferenceNumberPrefixMarker(Interface): """
] return u' '.join([name for name in names if name]) @property def initials(self): first_name = self.first_name or "" last_name = self.last_name or "" return first_name[:1].upper() + last_name[:2].capitalize() class UsernameValidator(validator.SimpleFieldValidator): """Two users can't have the same username. Because of #1043 it's possible that .username != .getUserName() so instead we rely on .username == .getUserId() which holds true since we don't do use_uuid_as_userid. """ def validate(self, value, force=False): membrane_tool = plone_api.portal.get_tool('membrane_tool') usernames = membrane_tool._catalog.uniqueValuesFor('exact_getUserId') if value in usernames: brains = membrane_tool.searchResults(exact_getUserId=value) if brains and self.context != brains[0].getObject(): raise Invalid(_("A user with this username already exists")) return super(UsernameValidator, self).validate(value) validator.WidgetValidatorDiscriminators(UsernameValidator, field=IUserProfile['username'])
if value is not None: catalog = api.portal.get_tool(name='portal_catalog') results = catalog({ 'Title': quote_chars(value), 'portal_type': ('collective.conferences.workshop', 'collective.conferences.talk') }) contextUUID = api.content.get_uuid(self.context) for result in results: if result.UID != contextUUID: raise Invalid(_(u'The talk title is already in use.')) validator.WidgetValidatorDiscriminators( ValidateWorkshopUniqueness, field=IWorkshop['title'], ) class WorkshopView(BrowserView): def canRequestReview(self): return api.user.has_permission('cmf.RequestReview', obj=self.context) def workshopLeaders(self): results = [] for rel in self.context.speaker: if rel.isBroken(): # skip broken relations continue obj = rel.to_object if api.user.has_permission('View', obj=obj):
enable_refresh = schema.Bool( title=_(u'Enable refresh'), description=_(u'Enable refresh of the current page.'), default=False, ) ttl = schema.Int( title=_(u'Time to live'), description=_(u'Number of seconds after which to reload the current page.',), default=300, ) alsoProvides(IRefresh, IFormFieldProvider) class TimeToLiveValidator(validator.SimpleFieldValidator): """z3c.form validator class for time to live""" def validate(self, value): """Validate the value on time to live input""" if value <= 0: raise Invalid(_(u'Value must be greater than zero.')) # set conditions for which fields the validator class applies validator.WidgetValidatorDiscriminators(TimeToLiveValidator, field=IRefresh['ttl']) # register the validator so it will be looked up by z3c.form machinery provideAdapter(TimeToLiveValidator)
# -*- coding: utf-8 -*- from Products.CMFPlone.browser.interfaces import ISendToForm from z3c.form import validator from zope.interface import Invalid class SendToEmailValidator(validator.SimpleFieldValidator): def validate(self, value): super(SendToEmailValidator, self).validate(value) if value and not self.context.portal_privacy.processingIsAllowed( 'send_to_form', user=value): raise Invalid(u'This person does not want to receive our emails') validator.WidgetValidatorDiscriminators( SendToEmailValidator, field=ISendToForm['send_to_address'], )
super(ValidateTrainingUniqueness, self).validate(value) if value is not None: catalog = api.portal.get_tool(name='portal_catalog') results = catalog({ 'Title': quote_chars(value), 'object_provides': ITraining.__identifier__ }) contextUUID = api.content.get_uuid(self.context) for result in results: if result.UID != contextUUID: raise Invalid(_(u'The training title is already in use.')) validator.WidgetValidatorDiscriminators( ValidateTrainingUniqueness, field=ITraining['title'], ) class TrainingView(BrowserView): def canRequestReview(self): return api.user.has_permission('cmf.RequestReview', obj=self.context) def trainingInstructors(self): results = [] for rel in self.context.speaker: if rel.isBroken(): # skip broken relations continue obj = rel.to_object if api.user.has_permission('View', obj=obj):
]): raise Invalid( _(u'error_file_and_preserved_as_paper', default=u"You don't select a file and document is also not " u"preserved in paper_form, please correct it.")) def has_referenced_document(self): RELATED_DOCUMENTS_KEY = 'form.widgets.IRelatedDocuments.relatedItems' related_documents = self.request.form.get(RELATED_DOCUMENTS_KEY) return related_documents is not None and len(related_documents) > 0 def is_preserved_as_paper(self): PAPER_KEY = 'form.widgets.IDocumentMetadata.preserved_as_paper' return self.request.form.get(PAPER_KEY) == [u'selected'] def has_file(self): FILE_KEY = 'form.widgets.file' FILE_ACTION_KEY = '%s.action' % FILE_KEY file_added = bool(self.request.form.get(FILE_KEY)) file_action = self.request.form.get(FILE_ACTION_KEY) if file_action == 'remove': return False return file_added or file_action validator.WidgetValidatorDiscriminators( FileOrPaperValidator, field=IDocumentMetadata['preserved_as_paper'], )
def validate(self, value): super(Z3CFormclamavValidator, self).validate(value) if getattr(value, '_validate_isVirusFree', False) or value is None: # validation is called multiple times for the same file upload return # TODO this reads the entire file into memory, there should be # a smarter way to do this result = '' try: result = _scanBuffer(value.data) except ScanError as e: logger.error('ScanError %s on %s.' % (e, value.filename)) raise Invalid("There was an error while checking " "the file for viruses: Please " "contact your system administrator.") if result: raise Invalid("Validation failed, file " "is virus-infected. (%s)" % (result)) else: # mark the file instance as already checked value._validate_isVirusFree = True validator.WidgetValidatorDiscriminators(Z3CFormclamavValidator, field=INamedField, widget=INamedFileWidget)
""" def validate(self, values): if values is None: return super(VocabularyNameValidator, self).validate(values) if values and self.request.form.get('form.widgets.values', None): raise interface.Invalid( _('field_edit_error_values_and_name', default= u"You can't set a vocabulary name AND vocabulary values. " u"Please clear values field or set no value here.")) return super(VocabularyNameValidator, self).validate(values) validator.WidgetValidatorDiscriminators( VocabularyNameValidator, field=se_schema.ITextLineChoice['vocabularyName']) @interface.implementer(interfaces.IFieldEditFormSchema) @component.adapter(schema_ifaces.ISet) def getMultiChoiceFieldSchema(field): return se_schema.ITextLineChoice MultiChoiceFactory = FieldFactory(schema.Set, _(u'label_multi_choice_field', default=u'Multiple Choice'), value_type=schema.Choice(values=[])) class TextLineMultiChoiceField(TextLineChoiceField):
def validate(self, value): try: previous_value = self.field.get(self.context) except AttributeError: previous_value = None if previous_value == value: try: ensure_image_size(value) except Invalid as invalid: IStatusMessage(self.context.REQUEST).add(invalid, "warn") else: ensure_image_size(value) validator.WidgetValidatorDiscriminators(ImageSizeValidator, context=IModule, field=INamedBlobImageField) @implementer(IModule, IQuestionContainer) class Module(Container): image = None caption = None file1 = None file1_caption = None file2 = None file2_caption = None file3 = None file3_caption = None file4 = None
if len(self.intern_receiver) == 0 and not self.extern_receiver: raise NoMail(_(u'You have to select a intern \ or enter a extern mail-addres')) @default_value(field=ISendDocumentSchema['documents_as_links']) def default_documents_as_links(data): """Set the client specific default (configured in the registry).""" registry = getUtility(IRegistry) proxy = registry.forInterface(ISendDocumentConf) return proxy.documents_as_links_default # put the validators validator.WidgetValidatorDiscriminators( DocumentSizeValidator, field=ISendDocumentSchema['documents'], ) validator.WidgetValidatorDiscriminators( AddressValidator, field=ISendDocumentSchema['extern_receiver'], ) provideAdapter(DocumentSizeValidator) provideAdapter(AddressValidator) class SendDocumentForm(form.Form): """A form to send documents over mail with.""" fields = field.Fields(ISendDocumentSchema)
- Teams are only allowed if the task/forwarding is in open state. - Admin unit changes are only allowed in open state. """ def validate(self, value): if value and not self.context.is_open(): data = {} data['responsible'] = value update_reponsible_field_data(data) validate_no_teams(self.context, data['responsible']) validate_no_admin_unit_change(self.context, data['responsible_client']) validator.WidgetValidatorDiscriminators( InProgressStateLimitiationsValidator, field=IAssignSchema['responsible'], ) class AssignTaskForm(Form): """Form for assigning task. """ fields = Fields(IAssignSchema) fields['responsible'].widgetFactory[INPUT_MODE] = ParameterizedWidget( KeywordWidget, async=True) ignoreContext = True allow_prefill_from_GET_request = True # XXX label = _(u'title_assign_task', u'Assign task')
text = schema.Text(title=_(u'label_response', default=u'Response'), description=_( u'help_complete_task_response', default=u'Enter a answer text which will be shown ' u'as response when the task is completed.'), required=False) # hidden: used to pass on the transition transition = schema.Choice(title=_("label_transition", default="Transition"), source=util.getTransitionVocab, required=True) validator.WidgetValidatorDiscriminators( NoCheckedoutDocsValidator, field=ICompleteSuccessorTaskSchema['documents']) class CompleteSuccessorTaskForm(Form): fields = Fields(ICompleteSuccessorTaskSchema) fields['documents'].widgetFactory = CheckBoxFieldWidget allow_prefill_from_GET_request = True # XXX label = _(u'title_complete_task', u'Complete task') ignoreContext = True @buttonAndHandler(_(u'button_save', default=u'Save'), name='save') def handle_save(self, action): data, errors = self.extractData()
class PasswordsMatchValidator(validator.SimpleFieldValidator): def validate(self, value): # XXX: hack to display the validation error next to the widget! name = self.view.widgets['password_confirmation'].name verify = self.request.get(name) if value is not None and value not in (verify, ): raise PasswordsDontMatch(value) class FlourishPasswordsMatchValidator(PasswordsMatchValidator): pass validator.WidgetValidatorDiscriminators( PasswordsMatchValidator, view=EmailSettingsEditView, field=IEmailSettingsEditForm['password']) validator.WidgetValidatorDiscriminators( FlourishPasswordsMatchValidator, view=FlourishEmailSettingsEditView, field=IEmailSettingsEditForm['password']) class HostnameValidator(validator.SimpleFieldValidator): def validate(self, value): # XXX: hack to display the validation error next to the widget! name = self.view.widgets['enabled'].name enabled = self.request.get(name) if enabled and enabled[0] in ('true', 'selected') and not value: raise HostnameIsRequired(value)