def clean(self): if self.from_component not in self._instance.components: raise ValidationError( 'Source component is not part of the application') if self.to_service.group not in self._instance.components: raise ValidationError( 'Destination service is not part of the application')
def validate(self, clean=True): Utility.validate_document_list(self.events) if Utility.check_empty_string(self.block_name): raise ValidationError( "Story path name cannot be empty or blank spaces") elif not self.events: raise ValidationError("Stories cannot be empty")
def validate(self, clean=True): if clean: self.clean() if Utility.check_empty_string(self.name) or Utility.check_empty_string( self.type): raise ValueError( "Slot name and type cannot be empty or blank spaces") error = "" if self.type == FloatSlot.type_name: if not self.min_value and not self.max_value: self.min_value = 0.0 self.max_value = 1.0 if self.min_value < self.max_value: error = "FloatSlot must have min_value < max_value" if not isinstance(self.initial_value, int): if error: error += "\n" error = "FloatSlot initial_value must be numeric value" ValidationError(error) elif self.type == CategoricalSlot.type_name: if not self.values: raise ValidationError( "CategoricalSlot must have list of categories in values field" )
def validate(self, clean=True): if Utility.check_empty_string(self.name): raise ValidationError("Form name cannot be empty or blank spaces") try: _validate_slot_mappings({self.name: self.mapping}) except Exception as e: raise ValidationError(e)
def validate(self, clean=True): if Utility.check_empty_string(self.name): raise ValidationError( "Action name cannot be empty or blank spaces") if self.name.startswith('utter_'): raise ValidationError("Action name cannot start with utter_")
def clean(self): """Check that all keys are known, all values are [0, 1].""" for loc, val in self.populations.items(): if loc not in KNOWN_LOCATIONS: raise ValidationError('No known location: {}'.format(loc)) if (val > 1) or (val < 0): raise ValidationError('Value in bad range.')
def clean(self): if str(self.nome).strip() == '': raise ValidationError('Campo nome não pode ser nulo') if str(self.clima).strip() == '': raise ValidationError('Campo clima não pode ser nulo') if str(self.terreno).strip() == '': raise ValidationError('Campo terreno não pode ser nulo')
def clean(self): """ Metodo de validacion de la clase Credit_Card. :exception ValidationError: excepcion lanzada cuando: *card_number no es numerico *expiration_month no es numerico o no esta en el rango [1:12] *expiration_year no es numerico *cvv no es numerico .. note:: se han añadido un par de comparaciones extras además de las pedidas en el enunciado para asegurar la integridad de los campos citados anteriormente """ if(not self.card_number.isdigit()): raise ValidationError("El numero de la tarjeta de credito no está formado exclusivamente de dígitos.") if(not self.expiration_month.isdigit() ): raise ValidationError("El mes de caducidad no está formado exclusivamente de dígitos.") month= float(self.expiration_month) #Usamos float porque a veces int da fallos. if (month < 1 or month > 12): raise ValidationError("El mes de caducidad introducido no es valido (los posibles van del 1 al 12).") if(not self.expiration_year.isdigit() ): raise ValidationError("El año de caducidad no está formado exclusivamente de dígitos.") if(not self.cvv.isdigit() ): raise ValidationError("El cvv no está formado exclusivamente de dígitos.")
def pre_save_post_validation(cls, sender, document, **kwargs): if document.md5: return # attachment already cross-referenced to existing one # b64 decode try: content = b64decode(document.content, validate=True) except binascii.Error: raise ValidationError( f"Attachment {document.name} not base64 encoded!") # check size size = len(content) if size > MAX_BYTES: raise ValidationError( f"Attachment {document.name} too large ({size} > {MAX_BYTES})!" ) # md5 resource = get_resource("attachments") document.md5 = get_md5(resource, document, COMPONENTS["attachments"]) # save to S3 and unset content s3_client.put_object( Bucket=BUCKET, Key=document.md5, ContentType=document.mime, Metadata={"name": document.name}, Body=content, ) document.content = str( size) # set to something useful to distinguish in post_init
def clean(self): """Called by Mongoengine on every ``.save()`` to the object. Updates date_modified, renders the markdown into the HTML fields, and validates datetimes to ensure the event ends after it starts. :raises: :class:`wtforms.validators.ValidationError` """ self.date_modified = now() if self.short_description_markdown: self.short_description = markdown.markdown( self.short_description_markdown, ['extra', 'smarty']) if self.long_description_markdown: self.long_description = markdown.markdown( self.long_description_markdown, ['extra', 'smarty']) if (self.start_date and self.end_date and self.start_date > self.end_date): raise ValidationError("Start date should always come before end " "date. Got (%r,%r)" % (self.start_date, self.end_date)) # Check times against None, because midnight is represented by 0. if (self.start_date == self.start_time and self.start_time is not None and self.end_time is not None and self.start_time > self.end_time): raise ValidationError("Start time should always come before end " "time. Got (%r,%r)" % (self.start_time, self.end_time))
def clean(self): """ Called by mongoengine before data is inserted into the db to verify that everything being inserted is valid """ garages_used = set(_GARAGES) # Make sure the date passed in is valid try: dateutil.parser.parse(self.date) except (TypeError, ValueError, OverflowError) as e: raise ValidationError(f"Couldn't parse date: {e.args[0]}") if len(self.garages) != 7: raise ValidationError( f'Expected an array of length 7 but got an array of length {len(self.garages)}' ) # Make sure each garage is entered exactly once for entry in self.garages: try: garages_used.remove(entry.name) except KeyError: raise ValidationError(f'Invalid garage name: {entry.name}') if len(garages_used) != 0: raise ValidationError(f'Entry missing garage(s): {garages_used}')
def clean(self): if (self.date_fulfilled is None) and (self.status == STATUS_FULFILLED): raise ValidationError('Request fulfilled but not specified when') if (self.date_fulfilled is not None) and (self.status != STATUS_FULFILLED): raise ValidationError( 'Request not fulfilled but date_fulfilled is set')
def apply_coupon(self, amount, user=None, product="all"): '''amount: amount to be paid''' if self.is_wrong_product(product): raise ValidationError("Sorry, this coupon is not valid for this product.") if self.is_expired(): raise ValidationError("This code has been expired") if user: if not self.is_valid(user): raise ValidationError("This code has already been used.") self.check_user_list(user) if not self.check_user_limit(): raise ValidationError("This code has already been used.") if self.type == 'percentage': discount = amount * self.value / 100 try: if self.max_discount and discount > self.max_discount: discount = self.max_discount except AttributeError: pass else: discount = self.value amount -= discount return amount if amount > 0 else 0
def greater_than_zero(val): try: if float(val) < 0.0 or float(val) == 0: raise ValidationError('Must be more than 0.0.') except ValueError: raise ValidationError('Value Error.') except TypeError: raise ValidationError('Type Error.')
def not_negative(val): try: if float(val) < 0.0: raise ValidationError('Cannot be a negative number.') except ValueError: raise ValidationError('Value Error.') except TypeError: raise ValidationError('Type Error.')
def validate(self, clean=True): if not self.title or not self.payload: raise ValidationError("title and payload must be present!") elif Utility.check_empty_string( self.title) or Utility.check_empty_string( self.payload.strip()): raise ValidationError( "Response title and payload cannot be empty or blank spaces")
def not_over_100(val): try: if float(val) > 100.0: raise ValidationError('Must be less than 100.0.') except ValueError: raise ValidationError('Value Error.') except TypeError: raise ValidationError('Type Error.')
def validate(self, clean=True): if clean: self.clean() if not Utility.check_empty_string(self.value) and self.type != 'slot': raise ValidationError("Value is allowed only for slot") if Utility.check_empty_string( self.name) and self.type != 'active_loop': raise ValidationError("Empty name is allowed only for active_loop")
def validate(self, clean=True): if Utility.check_empty_string(self.name): raise ValidationError( "Intent Name cannot be empty or blank spaces") else: if not Utility.special_match(self.name): raise ValidationError( "Intent Name must contains alphabets, number and underscore" )
def validate(self, clean=True): if clean: self.clean() from .utils import DataUtility if Utility.check_empty_string(self.block_name): raise ValidationError("rule name cannot be empty or blank spaces") elif not self.events: raise ValidationError("events cannot be empty") DataUtility.validate_flow_events(self.events, "RULE", self.block_name)
def validate_org_part(self): if not self.inn: raise ValidationError('ИНН не заполнен') if not self.kpp: raise ValidationError('КПП не заполнен') if len(self.inn) != 10: raise ValidationError('ИНН должен быть из 10 символов') if len(self.kpp) != 9: raise ValidationError('КПП должен быть из 9 символов')
def within_percentage_bounds(val): try: if float(val) > 100.0: raise ValidationError('Must be less than 100.0.') if float(val) < 0.0: raise ValidationError('Must be more than 0.0.') except ValueError: raise ValidationError('Value Error.') except TypeError: raise ValidationError('Type Error.')
def clean(self): self.validate(clean=False) #Comprobamos que el nombre de la linea es el mismo que el nombre del producto if(self.name != self.ref.nombre): raise ValidationError("El nombre de la linea no se corresponde con el nombre del producto referenciado") #Queremos comprobar que el precio total se corresponde con la mult de cantidad y precio if round(self.num_items * self.precio_item, 2) != self.total: #Vamos a redondear siempre a 2 decimales ya que a veces las multiplicaciones #de int * float dan valores con más decimales, en el caso de la linea 2, al multiplicar 3 * 3.55, nos devuelve 10.6499999999 en vez de 10.65 #Las operaciones siempre nos van a dar dos decimales, por lo que redondeamos a 2. raise ValidationError("El precio de la linea no se corresponde con el número de productos por su precio")
def visit(path, key, value): if key.startswith(" ") or key.endswith(" "): raise ValidationError(f"Strip whitespace in {key}") dot_path = delimiter.join(list(path) + [key]) if len(path) + 1 > max_depth + int(key in quantity_keys): raise ValidationError( f"max nesting ({max_depth}) exceeded for {dot_path}") valid_key(key) return True
def validate(self, clean=True): Utility.validate_document_list(self.events) if Utility.check_empty_string(self.block_name): raise ValidationError( "Story path name cannot be empty or blank spaces") elif not self.events: raise ValidationError("Stories cannot be empty") elif self.events[0].type != "user": raise ValidationError("Stories must start with intent") elif self.events[-1].type != "action": raise ValidationError("Stories must end with action")
def validate(self, clean=True): if Utility.check_empty_string(self.name): raise ValidationError( "Response name cannot be empty or blank spaces") elif not self.text and not self.custom: raise ValidationError( "Either Text or Custom response must be present!") else: if self.text: self.text.validate() elif self.custom: self.custom.validate()
def pre_validate(form): """Ensure that the versions dictionary contains keys of the form: <width>x<height>, where `width` and `height` are the size of the image at the path.""" for size, path in form.versions: try: width, height = PIL.Image.open(path).size if size != '%sx%s' % (width, height): raise ValidationError( 'Key %s improperly describes image %s', (size, path)) except IOError: raise ValidationError('File %s does not exist.' % form.default_path)
def clean(self): """ Metodo de validacion de la clase Order_LIne. :exception ValidationError: excepcion lanzada cuando: *el precio total difiere el calculado en base al numero de unidades y el precio individual *el nombre del producto y el de la linea de productos no encaja """ if(self.total_price!=self.ordered_products*self.product_price): raise ValidationError("El valor total de una linea del pedido no encaja con el precio de la unidad * el numero de unidades") if(self.product_name!=self.product.name): raise ValidationError("El nombre del producto y el de la línea del producto no encajan.")
def validate_entry(entry): """Validate individual Beta Diversity entry.""" all_sample_names = entry.keys() for sample_name, sub_level in entry.items(): level_sample_names = sub_level.keys() if all_sample_names != level_sample_names: message = f'Level {sample_name} did not contain correct sublevel samples.' raise ValidationError(message) for sub_level_name, value in sub_level.items(): if not isinstance(value, (int, float)): message = (f'Value for [{sample_name}][{sub_level_name}] ' '({value}) is not a number!') raise ValidationError(message)
def clean( self ): # Se lanza al llamar a .save(), permite hacer comprobaciones personalizadas. if self.precioTotalLinea != self.cantidadProductosComprados * self.precioProducto: raise ValidationError( f"El precio de la linea es {self.precioTotalLinea} pero deberia ser {self.cantidadProductosComprados * self.precioProducto}" ) if self.nombreProducto != self.referenciaProducto.nombre: raise ValidationError( f"El nombre del producto es {self.nombreProducto} pero referencia a {self.referenciaProducto.nombre}" )