def validate_form_inputs(self): form = self.request.form # Prefix and Leading zeros prefix_text = self.request.form.get('units-prefix-text', None) leading_zeros = self.request.form.get('units-leading-zeros', None) if not prefix_text or not leading_zeros: msg = u'Prefix text and Leading zeros are both required.' raise ValidationError(msg) # TODO: check if leading zeros has only zeros # check for valid integer values try: nr_items = int(form['units_nr_items']) except: msg = u'Item count must be an integer.' raise ValidationError(msg) if nr_items < 1: msg = u'Item count must be > 0.' raise ValidationError(msg) # Check that none of the IDs conflict with existing items start = form['units_start'] nr_items = int(form['units_nr_items']) ids = [x.id for x in self.context.objectValues()] for x in self.get_sequence(start, nr_items): id_unit = prefix_text + '-' + str(x).zfill(len(leading_zeros)) if id_unit in ids: msg = u'The ID %s already exists.' % id_unit raise ValidationError(msg)
def validate_form_input(self): subject_id = self.form.get('SubjectID') if not subject_id: raise ValidationError(['Subject ID cannot be empty!']) sampling_date = self.form.get('SamplingDate') if not sampling_date: raise ValidationError(['Sampling Date cannot be empty!'])
def validate_form_input(self): new_qty = int(self.form.get('Quantity', 0)) old_qty = int(self.context.Quantity or 0) if new_qty <= 0: raise ValidationError('Quantity of samples cannot be zero or less than zero!') if new_qty < old_qty: raise ValidationError('New number of samples cannot be less than the number of samples already created!')
def _validate(self, value): if len(value) not in (3, 6): raise ValidationError(_("Color length must be 3 or 6 characters")) for val in value: if val not in string.hexdigits: raise ValidationError( _("Color value must contain only valid hexadecimal color " "codes (numbers or letters between 'A' end 'F')")) super()._validate(value)
def setErrorsMessage(self, errors): for field in errors: if field not in self.widgets: continue error = ValidationError() error.doc = lambda: errors[field] view = getMultiAdapter( (error, self.request, self.widgets[ field], self.widgets[field].field, self, self.context), IErrorViewSnippet) view.update() self.widgets.errors += (view,) self.widgets[field].error = view self.status = self.formErrorsMessage
def validate_schema(action_data, schema): """Validate a dict against a schema, raise on error. """ errors = get_validation_errors(action_data, schema) if errors: raise ValidationError( "WebAction doesn't conform to schema (First error: %s)." % str(errors[0]))
def save(self, **data): ''' Create an InternalPrincipal with the user data. This method also grants the ViewMemberListing permission to the user. ''' login = data['login'] pau = getUtility(IAuthentication) principals = pau['principals'] # XXX: the login name must be unique; need better handling of this if login in principals: msg = _(u'Login name taken. Please choose a different one.') self.widgets['login']._error = ValidationError(msg) self.form_reset = False else: # create an instance of InternalPrincipal principal = InternalPrincipal(passwordManagerName='SHA1', **data) principals[login] = principal # grant the user permission to view the member listing permission_mngr = IPrincipalPermissionManager(grok.getSite()) permission_mngr.grantPermissionToPrincipal( 'plainlogindemo.ViewMemberListing', principals.prefix + login) self.redirect( self.url('login') + '?' + urlencode({'login': login}))
def save(self, **data): ''' Create an InternalPrincipal with the user data. This method also grants the ViewMemberListing permission to the user. ''' login = data['login'] pau = getUtility(IAuthentication) principals = pau['principals'] # create an instance of InternalPrincipal principal = InternalPrincipal(**data) try: principals[login] = principal except DuplicateIDError: # create a validation exception and assign it to the login field msg = _(u'Login name taken. Please choose a different one.') self.widgets['login']._error = ValidationError(msg) self.form_reset = False # preserve the values in the fields else: # grant the user permission to view the member listing permission_mngr = IPrincipalPermissionManager(grok.getSite()) permission_mngr.grantPermissionToPrincipal( 'plainlogindemo.ViewMemberListing', principals.prefix + login) self.redirect( self.url('login') + '?' + urlencode({'login': login}))
def build(self, schema): # Validate that the fieldname is known the the schema and the # saved query value validates properly before building the # query object: if not self.validate(schema): raise ValidationError('Unable to validate "%s"' % self.fieldname) return query_object(self, schema)
def save(self, **data): """ Create a Member and grant it the ViewMemberListing permission. """ login = data['login'] members = self.context['members'] member = Member(**data) try: # if we can already fetch a member object based on the requested # login id, then we create a validation exception and assign it # to the login field members[login] msg = _(u'Login name taken. Please choose a different one.') self.widgets['login']._error = ValidationError(msg) self.form_reset = False except KeyError: # login id is not taken so we save the member object # and grant the ViewMemberListing permission to the login id members[login] = member permission_mngr = IPrincipalPermissionManager(grok.getSite()) permission_mngr.grantPermissionToPrincipal( 'babylogindemo.ViewMemberListing', 'babylogindemo' + login) self.redirect( self.url('login') + '?' + urlencode({'login':login}) )
def validate_form_input(self): subject_id = self.form.get('SubjectID') if not subject_id: raise ValidationError(['Subject ID cannot be empty!']) date_created = self.form.get('DateCreated') if not date_created: raise ValidationError(['Date Created cannot be empty!']) new_qty = int(self.form.get('Quantity', 0)) old_qty = int(self.context.Quantity or 0) if new_qty <= 0: raise ValidationError( 'Quantity of samples cannot be zero or less than zero!') if new_qty < old_qty: raise ValidationError( 'New number of samples cannot be less than the number of samples already created!' )
def _validateAndNormalizeEmail(self, address): """ Validates and normalizes an email address.""" address = address.strip() if not address: raise ValidationError('No email address given') try: a = rfc822.AddressList(address) except: raise ValidationError('Email address was not compliant with ' 'rfc822') if len(a.addresslist) > 1: raise ValidationError('More than one email address was given') try: address = a.addresslist[0][1] except: raise ValidationError('Unexpected validation error') if not address: raise ValidationError('No email address given') return address
def validate_no_unknown_fields(action_data, schema): """Validate that data only contains known fields. No other validations are performed though. This is needed in situations where only have partial webaction data, like on PATCH / update(), and therefore can't expect invariant validations to succeed. """ errors = get_unknown_fields(action_data, schema) if errors: raise ValidationError( "WebAction doesn't conform to schema (First error: %s)." % str(errors[0]))
def get_si_storages(self): """ return storages which could store stock items """ si_storages = [] for uid in self.form['si-storage-uids'].split(','): brain = self.bsc(UID=uid) if not brain: raise ValidationError(u'Bad uid. This should not happen.') si_storages.append(brain[0].getObject()) return si_storages
def get_si_storages(storage_uids, portal_catalog): """ return storage which could store stock-items """ si_storage = [] for uid in storage_uids: brain = portal_catalog(UID=uid) if not brain: raise ValidationError(u'Bad uid. This should not happen.') si_storage.append(brain[0].getObject()) return si_storage
def get_si_storages(self): """ return objects of the selected stock items storages """ uc = getToolByName(self.context, 'uid_catalog') si_storages = [] for uid in self.form['si_storage_uids'].split(','): brain = uc(UID=uid) if not brain: raise ValidationError(u'Bad uid. Should not happen.') si_storages.append(brain[0].getObject()) return si_storages
def validate_form_inputs(self): """Validate form inputs """ form = self.request.form if not form['title']: raise ValidationError( 'Title should be specified for this invoice!') if not form['invoice_services']: raise ValidationError('Invoice service is required!') if form['startdate'] and form['enddate']: if form['enddate'] < form['startdate']: raise ValidationError( u"Start date, '%s', shouldn't be greater than End date, '%s'!" % (form['startdate'], form['enddate'])) return { 'title': form['title'], 'project_uid': form['Project_uid'], 'services': form['invoice_services'], 'start_date': form['startdate'], 'end_date': form['enddate'] }
def validate_form_inputs(self): form = self.request.form title_template = form.get('titletemplate', None) id_template = form.get('idtemplate', None) if not (title_template and id_template): raise ValidationError(u'ID and Title template are both required.') if not ('{id}' in title_template and '{id}' in id_template): raise ValidationError(u'ID and Title templates must contain {id} ' u'for ID sequence substitution') try: seq_start = int(form.get('seq_start', None)) except: raise ValidationError( u'Sequence start and all counts must be integers') first_kit_limit = form.get('first_kit_limit', None) last_kit_limit = form.get('last_kit_limit', None) if not first_kit_limit or not last_kit_limit: raise ValidationError( u'Kits range is required. Or project select has no kits!') kits = self.kits_between_limits(first_kit_limit, last_kit_limit) count = len(kits) biospecimen_per_kit = int(form.get('biospecimen_per_kit', None)) biospecimen_count = count * biospecimen_per_kit # Check that none of the IDs conflict with existing items ids = [x.id for x in self.context.objectValues()] for x in range(biospecimen_count): check = id_template.format(id=seq_start + x) if check in ids: raise ValidationError(u'The ID %s exists, cannot be created.' % check) # Check that the storages selected has sufficient positions to contain # the biospecimen to generate. bio_storages = self.get_biospecimen_storages() if all( [IManagedStorage.providedBy(storage) for storage in bio_storages]): nr_positions = self.count_storage_positions(bio_storages) if biospecimen_count > nr_positions: raise ValidationError( u"Not enough kit storage positions available. Please select " u"or create additional storages for kits.") return { 'title_template': title_template, 'id_template': id_template, 'seq_start': seq_start, 'first_kit_limit': first_kit_limit, 'last_kit_limit': last_kit_limit, 'kits': kits, 'biospecimen_per_kit': biospecimen_per_kit, 'biospecimen_count': biospecimen_count, 'storages': bio_storages }
def validate_form_inputs(self): form = self.request.form # Prefix and Leading zeros prefix_text = self.request.form.get('unmanaged-prefix-text', None) leading_zeros = self.request.form.get('unmanaged-leading-zeros', []) if not prefix_text: msg = u'Prefix text is required.' raise ValidationError(msg) # TODO: check if leading zeros has only zeros # check for valid integer values try: nr_items = int(self.request.form.get('unmanaged-nr-items', None)) except: msg = u'Item count must be an integer.' raise ValidationError(msg) if nr_items < 1: msg = u'Item count must be > 0' raise ValidationError(msg) # Check that none of the IDs conflict with existing items start = int(form['unmanaged-start']) nr_items = int(form['unmanaged-nr-items']) ids = [x.id for x in self.context.objectValues()] for x in self.get_sequence(start, nr_items): id_storage = prefix_text + '-' + str(x).zfill( len(leading_zeros) + 1) if id_storage in ids: msg = u'The ID %s already exists.' % x raise ValidationError(msg) # verify storage_type interface selection storage_types = form.get('umanaged-storage-types', []) if not storage_types: raise ValidationError( u'To create managed storage, at least one storage type must be selected.' )
def count_storage_positions(storages): """"Return the number of items that can be stored in storages. This method is called in case all the storages are of type Managed. """ count = 0 for storage in storages: # If storage is a ManagedStorage, increment count for each # available StoragePosition if IManagedStorage.providedBy(storage): count += storage.getFreePositions() else: raise ValidationError("Storage %s is not a valid storage type" % storage) return count
def fromUnicode(self, u): name = str(u.strip()) # special case, mostly for interfaces if name == '*': return None try: value = self.context.resolve(name) except ConfigurationError as v: raise ValidationError(v) self.validate(value) return value
def validate_form_inputs(self): form = self.request.form title_template = form.get('titletemplate', None) id_template = form.get('idtemplate', None) if not (title_template and id_template): raise ValidationError(u'ID and Title template are both required.') if not ('{id}' in title_template and '{id}' in id_template): raise ValidationError(u'ID and Title templates must contain {id} ' u'for ID sequence substitution') try: seq_start = int(form.get('seq_start', None)) kit_count = int(form.get('kit_count', None)) except: raise ValidationError( u'Sequence start and all counts must be integers') # verify ID sequence start if seq_start < 1: raise ValidationError(u'Sequence Start may not be < 1') # verify number of kits if kit_count < 1: raise ValidationError(u'Kit count must not be < 1') # KIT storage destination is required field. kit_storage_uids = form.get('kit_storage_uids', '') if not kit_storage_uids: raise ValidationError(u'You must select the Storage where the kit ' u'items will be stored.') # Stock Item storage (where items will be taken from) is required si_storage_uids = form.get('si_storage_uids', '') if not si_storage_uids: raise ValidationError(u'You must select the Storage where the ' u'stock items will be taken from.') # Check that none of the IDs conflict with existing items ids = [x.id for x in self.context.objectValues()] for x in range(kit_count): check = id_template.format(id=seq_start + x) if check in ids: raise ValidationError(u'The ID %s exists, cannot be created.' % check)
def __init__(self, **kwargs): """Object init Kwargs: [see sparc.event.event.SparcEvent] query: IQuery object results: IQueryResultSet object """ super(QueryEvent, self).__init__(**kwargs) self.query = kwargs['query'].query if not IQueryResultSet.providedBy(kwargs['results']): raise ValidationError( 'expected IQueryResultSet for results, got: {}'.format( "'" + str(kwargs['results']) + "'")) self.results = kwargs['results']
def validate_form_inputs(self): """Validate form inputs """ form = self.request.form title_template = form.get('titletemplate', None) id_template = form.get('idtemplate', None) if not (title_template and id_template): raise ValidationError(u'ID and Title template are both required.') if not ('{id}' in title_template and '{id}' in id_template): raise ValidationError(u'ID and Title templates must contain {id} ' u'for ID sequence substitution') try: seq_start = int(form.get('seq_start', None)) except: raise ValidationError( u'Sequence start and all counts must be integers') project_uid = form.get('Project_uid', None) if not project_uid: raise ValidationError( u'Project is required and should be not "None"') first_bio_limit = form.get('first_biosepcimen_limit', None) last_bio_limit = form.get('last_biospecimen_limit', None) if not first_bio_limit or not last_bio_limit: raise ValidationError( u'Kits range is required. Or project select has no kits!') biospecimens = self.bio_between_limits(first_bio_limit, last_bio_limit, project_uid) bio_count = len(biospecimens) aliquot_count = int(form.get('aliquot_count', None)) count = bio_count * aliquot_count # Check that none of the IDs conflict with existing items ids = [x.id for x in self.context.objectValues('Aliquot')] for x in range(count): check = id_template.format(id=seq_start + x) if check in ids: raise ValidationError(u'The ID %s exists, cannot be created.' % check) return { 'title_template': title_template, 'id_template': id_template, 'seq_start': seq_start, 'project_uid': project_uid, 'first_bio_limit': first_bio_limit, 'last_bio_limit': last_bio_limit, 'biospecimens': biospecimens, 'count': count, 'aliquot_count': aliquot_count, }
def stockitems_for_template(self, template): """ Return stockitems of kit template's products """ stockitems = [] for product in template.getProductList(): items = self.product_stockitems(product['product_uid']) items = self.filter_stockitems_by_storage_location(items) quantity = int(product['quantity']) if len(items) < quantity: msg = u"There is insufficient stock available for the " \ u"product '%s'." % product['product'] self.form_error(msg) raise ValidationError(msg) stockitems += items[:quantity] return stockitems
def fromUnicode(self, u): name = str(u.strip()) # queryUtility can never raise ComponentLookupError value = queryUtility(IMenuItemType, name) if value is not None: self.validate(value) return value try: value = self.context.resolve('zope.app.menus.' + name) except ConfigurationError as v: try: value = self.context.resolve(name) except ConfigurationError as v: raise ValidationError(v) self.validate(value) return value
def stockitems_for_template(self, template): """ Return stockitems of kit template's products """ stockitems = [] for product in template.getProductList(): brains = self.bika_setup_catalog( portal_type='StockItem', getProductUID=product['product_uid'], review_state='available') items = [b.getObject() for b in brains] items = self.filter_stockitems_by_storage_location(items) quantity = int(product['quantity']) if len(items) < quantity: raise ValidationError( u"There is insufficient stock available for the " u"product '%s'." % product['product']) stockitems += items[:quantity] return stockitems
def fromUnicode(self, u): name = str(u.strip()) try: value = queryUtility(IMenuItemType, name) except ComponentLookupError: # The component architecture is not up and running. pass else: if value is not None: self.validate(value) return value try: value = self.context.resolve('zope.app.menus.' + name) except ConfigurationError, v: try: value = self.context.resolve(name) except ConfigurationError, v: raise ValidationError(v)
def validate_form_inputs(self): form = self.request.form # Prefix and Leading zeros prefix_text = self.request.form.get('managed-prefix-text', None) leading_zeros = self.request.form.get('managed-leading-zeros', []) if not prefix_text: msg = u'Prefix text is required.' raise ValidationError(msg) # TODO: check if leading zeros has only zeros # check for valid integer values try: nr_items = int(form.get('managed-nr-items', None)) fnrp = form.get('managed-positions', 0) if not fnrp: fnrp = 0 nr_positions = int(fnrp) except: msg = u'Item and position count must be numbers' raise ValidationError(msg) if nr_items < 1: msg = u'Item count must be > 0.' raise ValidationError(msg) if nr_positions < 1: msg = u'Position count must be > 1.' raise ValidationError(msg) # verify storage_type interface selection storage_types = form.get('managed-storage-types', []) if any([storage_types, nr_positions]) \ and not all([storage_types, nr_positions]): raise ValidationError( u'To create managed storage, at least one storage type must be ' u'selected, and the number of storage positions must be > 0.') # Check that none of the IDs conflict with existing items start = form['managed-start'] nr_items = int(form['managed-nr-items']) ids = [x.id for x in self.context.objectValues()] for x in self.get_sequence(start, nr_items): id_storage = prefix_text + '-' + str(x).zfill( len(leading_zeros) + 1) if id_storage in ids: msg = u'The ID %s already exists.' % id_storage raise ValidationError(msg)
def count_storage_positions(self, storages): """Return the number of items that can be stored in storages. If any of these storages are "UnmanagedStorage" objects, then the result will be -1 as we cannot know how many items can be stored here. """ count = 0 for storage in storages: # If storage is an unmanaged storage, we no longer care about # "number of positions". if IUnmanagedStorage.providedBy(storage): return -1 # If storage is a StoragePosition, simply increment the count. elif IStoragePosition.providedBy(storage): count += 1 # If storage is a ManagedStorage, increment count for each # available StoragePosition elif IManagedStorage.providedBy(storage): count += storage.get_free_positions() else: raise ValidationError( "Storage %s is not a valid storage type" % storage) return count