def clean(self): try: self.get_entry() except ValueError as e: raise ValidationError("Invalid crontab expression: %s" % e) if not self.get_handler(): raise ValidationError("Invalid handler")
def clean(self): self.from_number = clean_number(self.from_number or "") if not self.from_number: raise ValidationError("Empty from_number") self.to_number = clean_number(self.to_number or "") if not self.to_number: raise ValidationError("Empty to_number") if self.to_number < self.from_number: self.from_number, self.to_number = self.to_number, self.from_number super(PhoneRange, self).clean() # Check overlapped ranges q = Q(dialplan=self.dialplan.id) & ( Q(from_number__gt=self.from_number, from_number__lte=self.to_number, to_number__gt=self.to_number) | Q(to_number__lt=self.to_number, from_number__lt=self.from_number, to_number__gte=self.from_number) | Q(from_number=self.from_number, to_number=self.to_number)) if self.id: q &= Q(id__ne=self.id) rr = PhoneRange.objects.filter(q).first() if rr: raise ValidationError("Overlapped ranges: %s - %s (%s)" % (rr.from_number, rr.to_number, rr.name)) q = { "dialplan": self.dialplan, "from_number": self.from_number, "to_number": self.to_number } if self.id: q["exclude_range"] = self self.parent = PhoneRange.get_closest_range(**q)
def test_serialize_mongoengine_validation_error(self): from flask_mongorest.views import serialize_mongoengine_validation_error error = ValidationError(errors={ 'a': ValidationError('Invalid value') }) result = serialize_mongoengine_validation_error(error) self.assertEqual(result, { 'field-errors': { 'a': 'Invalid value', } }) error = ValidationError('Invalid value') result = serialize_mongoengine_validation_error(error) self.assertEqual(result, { 'error': 'Invalid value' }) error = ValidationError(errors={ 'a': 'Invalid value' }) result = serialize_mongoengine_validation_error(error) self.assertEqual(result, { 'field-errors': { 'a': 'Invalid value', } })
def validate_username(username): valid_chars = string.ascii_letters + string.digits + '-_' if not all([char in valid_chars for char in username]): raise ValidationError('Username contains invalid characters.') if username[0] not in string.ascii_letters: raise ValidationError('Username must begin with a letter.')
def clean(self): self.validate(clean=False) if len(self.dni) != 9: raise ValidationError("La longitud del DNI no es correcta") if len(self.f_nac) != 10: raise ValidationError( "La longitud de la fecha de nacimiento no es correcta") listaLetras = [ 'T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E' ] letra = self.dni[8] if letra not in string.ascii_uppercase: raise ValidationError( "La letra del DNI no se ha encontrado o tiene un formato incorrecto" ) numero = int(self.dni[0:8]) if letra != listaLetras[numero % 23]: raise ValidationError("La letra del DNI es incorrecta") fnac1 = self.f_nac[0:4] fnac2 = self.f_nac[5:7] fnac3 = self.f_nac[8:10] if self.f_nac[4] != "-" or self.f_nac[7] != "-" or not fnac1.isnumeric( ) or not fnac2.isnumeric() or not fnac3.isnumeric( ) or not int(fnac2) < 13 or not int(fnac3) < 31: raise ValidationError( "El formato de la fecha de nacimiento es incorrecto")
def clean(self): if "/" in self.domain: msg = "Domain should be in format 'example.com'" raise ValidationError(msg) if len(self.username) < 1: msg = "Username should not be empty" raise ValidationError(msg)
def validate(self, clean=True): if self.action_name is None or not self.action_name.strip(): raise ValidationError("Action name cannot be empty") if self.http_url is None or not self.http_url.strip(): raise ValidationError("URL cannot be empty") if isinstance(validators.url(self.http_url), ValidationFailure): raise ValidationError("URL is malformed") if self.request_method.upper() not in ("GET", "POST", "PUT", "DELETE"): raise ValidationError("Invalid HTTP method")
def validate(self, clean=True): from .utils import ActionUtility if ActionUtility.is_empty(self.key): raise ValidationError( "key in http action parameters cannot be empty") if self.parameter_type == "slot" and ActionUtility.is_empty( self.value): raise ValidationError("Provide name of the slot as value")
def validate_content_type(value: int) -> None: # Check is valid content type try: ct = ContentType(value) except ValueError as e: raise ValidationError(str(e)) # Check content type is image if not ct.is_image: raise ValidationError("Image is required")
def clean(self): try: valid_fields = schemas[self.entry_type] except KeyError: msg = 'There is no schema defined for %s' % self.entry_type raise ValidationError(msg) for dynamic_field in self.entry._dynamic_fields.keys(): if dynamic_field not in valid_fields: msg = '%s is not a valid field' % dynamic_field raise ValidationError(msg)
def validate(self, clean=True): if (Utility.check_empty_string(self.email) or Utility.check_empty_string(self.first_name) or Utility.check_empty_string(self.last_name) or Utility.check_empty_string(self.password)): raise ValidationError( "Email, FirstName, LastName and password cannot be empty or blank space" ) elif isinstance(email(self.email), ValidationFailure): raise ValidationError("Please enter valid email address")
def clean(self): if self.type.name in { "Composed", "Combined" } and (self.direction != "s" or self.gender != "s"): raise ValidationError( 'Direction and gender fields on Composed or Combined connection type must be "s"' ) if self.composite_pins and not rx_composite_pins_validate.match( self.composite_pins): raise ValidationError("Composite pins not match format: N-N") super().clean()
def save(self, *args, **kwargs): if self.direct_objects: if any(o_elem.object is None for o_elem in self.direct_objects): raise ValidationError("Object line is Empty") if self.direct_segments: for elem in self.direct_segments: try: elem.segment = elem.segment except Exception: raise ValidationError("Segment line is Empty") super(Maintenance, self).save(*args, **kwargs)
def validate(self, clean=True): from kairon.shared.actions.utils import ActionUtility if clean: self.clean() try: ActionUtility.validate_pipedrive_credentials(self.domain, self.api_token) if Utility.check_empty_string(self.metadata.get('name')): raise ValidationError("metadata: name is required") except Exception as e: raise ValidationError(e)
def clean(self): item_available_hours = self.item_available_hours if len(item_available_hours) != 7: raise ValidationError( "Total week days not matching. Need to fill for all week") for day_opening_timings in item_available_hours: opens_at = day_opening_timings.get("opens_at") closes_at = day_opening_timings.get("closes_at") if closes_at < opens_at or not isinstance( closes_at, int) or not isinstance(opens_at, int): raise ValidationError("Invalid Opening and closing hours")
def validate(self, clean=True): if clean: self.clean() from .utils import ActionUtility if ActionUtility.is_empty(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 get_user_details(email: str): user = AccountProcessor.get_user(email) if not user["status"]: raise ValidationError("Inactive User please contact admin!") bot = AccountProcessor.get_bot(user["bot"]) account = AccountProcessor.get_account(user["account"]) if not bot["status"]: raise ValidationError("Inactive Bot Please contact system admin!") if not account["status"]: raise ValidationError( "Inactive Account Please contact system admin!") return user
def validate(self, clean=True): """Ensure that all fields' values are valid and that required fields are present. Raises :class:`ValidationError` if any of the fields' values are found to be invalid. """ # Ensure that each field is matched to a valid value errors = {} if clean: try: self.clean() except ValidationError as error: errors[NON_FIELD_ERRORS] = error # Get a list of tuples of field names and their current values fields = [ ( self._fields.get(name, self._dynamic_fields.get(name)), self._data.get(name), ) for name in self._fields_ordered ] EmbeddedDocumentField = _import_class("EmbeddedDocumentField") GenericEmbeddedDocumentField = _import_class("GenericEmbeddedDocumentField") for field, value in fields: if value is not None: try: if isinstance( field, (EmbeddedDocumentField, GenericEmbeddedDocumentField) ): field._validate(value, clean=clean) else: field._validate(value) except ValidationError as error: errors[field.name] = error.errors or error except (ValueError, AttributeError, AssertionError) as error: errors[field.name] = error elif field.required and not getattr(field, "_auto_gen", False): errors[field.name] = ValidationError( "Field is required", field_name=field.name ) if errors: pk = "None" if hasattr(self, "pk"): pk = self.pk elif self._instance and hasattr(self._instance, "pk"): pk = self._instance.pk message = "ValidationError ({}:{}) ".format(self._class_name, pk) raise ValidationError(message, errors=errors)
def get_user_details(email: str): """ Get details of the user such as account name and the chatbot he/she is training based on email input """ user = AccountProcessor.get_user(email) if not user["status"]: raise ValidationError("Inactive User please contact admin!") bot = AccountProcessor.get_bot(user["bot"]) account = AccountProcessor.get_account(user["account"]) if not bot["status"]: raise ValidationError("Inactive Bot Please contact system admin!") if not account["status"]: raise ValidationError("Inactive Account Please contact system admin!") return user
def clean(self): self.validate(clean=False) if not isinstance(self.ref, Producto): raise ValidationError("La referencia a un producto no es correcta") if self.name != self.ref.nombre: raise ValidationError( "El nombre de el producto referenciado no se corresponde con el de la línea" ) if self.total != self.num_items * self.precio_item: raise ValidationError( "El precio total de la línea no se corresponde con el precio individual por número de items" )
def clean(self): super(PhoneNumber, self).clean() # Check number is valid integer self.number = clean_number(self.number or "") if not self.number: raise ValidationError("Empty phone number") # Change parent self.phone_range = PhoneRange.get_closest_range( dialplan=self.dialplan, from_number=self.number) # Set profile when necessary if not self.profile: if not self.phone_range: raise ValidationError("Either range or profile must be set") self.profile = self.phone_range.profile.default_number_profile
def validate(self, clean=True): """Ensure that all fields' values are valid and that required fields are present. """ # Ensure that each field is matched to a valid value errors = {} if clean: try: self.clean() except ValidationError as error: errors[NON_FIELD_ERRORS] = error # Get a list of tuples of field names and their current values fields = [(field, self._data.get(name)) for name, field in list(self._fields.items())] if self._dynamic: fields += [(field, self._data.get(name)) for name, field in list(self._dynamic_fields.items())] EmbeddedDocumentField = _import_class("EmbeddedDocumentField") GenericEmbeddedDocumentField = _import_class( "GenericEmbeddedDocumentField") for field, value in fields: if value is not None: try: if isinstance( field, (EmbeddedDocumentField, GenericEmbeddedDocumentField)): field._validate(value, clean=clean) else: field._validate(value) except ValidationError as error: errors[field.name] = error.errors or error except (ValueError, AttributeError, AssertionError) as error: errors[field.name] = error elif field.required and not getattr(field, '_auto_gen', False): errors[field.name] = ValidationError('Field is required', field_name=field.name) if errors: pk = "None" if hasattr(self, 'pk'): pk = self.pk elif self._instance: pk = self._instance.pk message = "ValidationError (%s:%s) " % (self._class_name, pk) raise ValidationError(message, errors=errors)
def __init__(self, model, **kwargs): if not issubclass(model, Model): raise ValidationError("Argument to ForeignKeyField constructor " "must be a Model class") self.document_type = model self.set_dereference() super(ForeignKeyField, self).__init__(**kwargs)
def hand_clean_DELETE(self): """ We don't validate the 'DELETE' field itself because on templates it's not rendered using the field information, but just using a generic "deletion_field" of the InlineModelAdmin. """ if self.cleaned_data.get(DELETION_FIELD_NAME, False): collector = NestedObjects() collector.collect([self.instance]) if collector.protected: objs = [] for p in collector.protected: objs.append( # Translators: Model verbose name and instance representation, suitable to be an item in a list _('%(class_name)s %(instance)s') % { 'class_name': p._meta.verbose_name, 'instance': p} ) params = {'class_name': self._meta.model._meta.verbose_name, 'instance': self.instance, 'related_objects': get_text_list(objs, _('and'))} msg = _("Deleting %(class_name)s %(instance)s would require " "deleting the following protected related objects: " "%(related_objects)s") raise ValidationError(msg, code='deleting_protected', params=params)
def validate_post_data(self, data, task): ''' TB made generic. ''' if not data: self.send_error(404) user = None try: user = User.objects.get(username=data['username']) except User.DoesNotExist: raise HTTPError(404, **{'reason': 'User Not Found'}) if user not in task.project.members: raise HTTPError(404, **{'reason': 'User Not Found'}) self.data['username'] = user pat = "^-?[0-9]+$" if 'logged_effort' in data.keys() and data['logged_effort']: val = re.findall(pat, data['logged_effort']) if not val: raise HTTPError(403, reason='Efforts should be only in integers') if 'estimated_effort' in data.keys() and data['estimated_effort']: val = re.findall(pat, data['estimated_effort']) if not val: raise HTTPError( 403, **{'reason': 'Efforts should be only in integers.'}) if (task.created_by == self.current_user) or (self.current_user in task.project.admin): pass elif task.assigned_to and (task.assigned_to != self.current_user): raise ValidationError('You were not assigned this task')
def get_user_details(email: str): """ fetches complete user details, checks for whether it is inactive :param email: login id :return: dict """ user = AccountProcessor.get_user(email) AccountProcessor.check_email_confirmation(user["email"]) if not user["status"]: raise ValidationError("Inactive User please contact admin!") account = AccountProcessor.get_account(user["account"]) if not account["status"]: raise ValidationError( "Inactive Account Please contact system admin!") return user
def clean(self): self.validate(clean=False) sumaPrecio = 0 productosReferenciados = {} for i in self.lineas: sumaPrecio += i.total if i.ref not in productosReferenciados.keys(): productosReferenciados[i.ref] = True else: raise ValidationError( "Hay más de una línea que referencia un mismo producto") if sumaPrecio != self.total: raise ValidationError( "El precio total no se corresponde a la suma de los precios de cada item" )
def validate_flow_events(events, type, name): Utility.validate_document_list(events) if events[0].type != "user": raise ValidationError("First event should be an user") if events[len(events) - 1].type == "user": raise ValidationError("user event should be followed by action") intents = 0 for i, j in enumerate(range(1, len(events))): if events[i].type == "user": intents = intents + 1 if events[i].type == "user" and events[j].type == "user": raise ValidationError("Found 2 consecutive user events") if type == "RULE" and intents > 1: raise ValidationError(f"""Found rules '{name}' that contain more than user event.\nPlease use stories for this case""")
def validate(self, clean=True): if clean: self.clean() if self.action_name is None or not self.action_name.strip(): raise ValidationError("Action name cannot be empty") if self.smtp_url is None or not self.smtp_url.strip(): raise ValidationError("URL cannot be empty") if not Utility.validate_smtp(self.smtp_url, self.smtp_port): raise ValidationError("Invalid SMTP url") elif isinstance(email(self.from_email), ValidationFailure): raise ValidationError("Invalid From or To email address") else: for to_email in self.to_email: if isinstance(email(to_email), ValidationFailure): raise ValidationError("Invalid From or To email address")
def save(self, *args, **kwargs): created = False if self._created: created = self._created if self.direct_objects: if any(o_elem.object is None for o_elem in self.direct_objects): raise ValidationError("Object line is Empty") if self.direct_segments: for elem in self.direct_segments: try: elem.segment = elem.segment except Exception: raise ValidationError("Segment line is Empty") super().save(*args, **kwargs) if created: self.update_affected_objects_maintenance() self.auto_confirm_maintenance()