def __call__(self, form, field): if "password" not in field.name and isinstance(field.data, str): field.data = field.data.strip() if not field.data: if self.message is None: message = field.gettext("This field is be not empty.") else: message = self.message field.errors[:] = [] raise StopValidation(message)
def __call__(self, form, field): if not (all(isinstance(item, FileStorage) for item in field.data) and field.data): return for data in field.data: filename = data.filename.lower() if isinstance(self.upload_set, Iterable): if any(filename.endswith("." + x) for x in self.upload_set): return raise StopValidation(self.message or field.gettext( "File does not have an approved extension: {extensions}" ).format(extensions=", ".join(self.upload_set))) if not self.upload_set.file_allowed(field.data, filename): raise StopValidation( self.message or field.gettext("File does not have an approved extension."))
def __call__(self, form, field): try: other_field = getattr(form, self.other_field_name) other_val = other_field.data if other_val in self.values: if not field.data or isinstance(field.data, basestring) and not field.data.strip(): if self.message is None: self.message = 'This field is required.' field.errors[:] = [] raise StopValidation(self.message % {'other_field': other_field.label.text, 'value': other_val}) except AttributeError: pass
def is_alpha_numeric(form, field): """ Validator to check the field is alpha numeric. """ if field.data is not None and not str(field.data).replace(' ', '').isalnum(): # The field is not a float. field.errors[:] = [ 'Must be and alpha-numerical string, and not contain symbols.' ] # Stop all further validations. raise StopValidation()
def __call__(self, form, field): if field.data is None or (isinstance(field.data, string_types) and not field.data.strip()) or (isinstance( field.data, (list, dict)) and not field.data): if self.message is None: message = field.gettext('This field is required.') else: message = self.message field.errors[:] = [] raise StopValidation(message)
def __call__(self, form, field): other_field = form._fields.get(self.other_field_name) if other_field is None: raise Exception( 'no field named "%s" in form' % other_field.label.text if other_field.label else self.other_field_name ) if bool(other_field.data) and not bool(field.data): raise StopValidation( 'You filled out "%s" but left this blank -- please fill this out as well.' % other_field.label.text if other_field.label else self.other_field_name )
def __call__(self, form, field): other_field = form._fields.get(self.other_field_name) if other_field is None: raise Exception( 'no field named "%s" in form' % other_field.label.text if other_field.label else self.other_field_name ) if bool(other_field.data) and bool(field.data): raise StopValidation( 'You cannot choose both this and "%s"' % other_field.label.text if other_field.label else self.other_field_name )
def __call__(self, form, field): other_field = form._fields.get(self.other_field_name) if other_field is None: raise Exception( 'no field named "%s" in form' % other_field.label.text if other_field.label else self.other_field_name ) if not bool(other_field.data) and not bool(field.data): raise StopValidation( 'You must fill out either this or "%s"' % other_field.label.text if other_field.label else self.other_field_name )
def validate_self_password(form, field): current_user = form.kwargs.get('current_user', None) if current_user is None: return if not current_user.password: return if not form.password.data: return if not current_user.check_password(field.data): _ = field.gettext raise StopValidation(_('False password'))
def _make_optional(form, field): # Search the form for the "other field" object _other_field = form._fields.get(other_field) # Check if the other field exists in form if other_field is None: raise Exception('No field named "%s" in form' % other_field) # If the other field has data if bool(_other_field.data): raise StopValidation()
def __call__(self, form, field): depfield = getattr(form, self.field_name) for dependency in self.dependencies: if callable(dependency) and dependency(depfield, form=form): if not field.raw_data or isinstance(field.raw_data[0], string_types): if hasattr(field, "clear_errors"): field.clear_errors() else: if isinstance(field.errors, list): field.errors[:] = [] else: field.errors = [] raise StopValidation()
def __call__(self, form, field): # check if some data is entered in field if field.raw_data is None or ( isinstance(field.data, string_types) and not field.data.strip() ): # get error message if self.message is None: self.message = field.gettext('This field is required.') # clear all errors for this field field.errors[:] = [] # stop validation and raise this error raise StopValidation(self.message)
def __call__(self, form, field): if callable(self.message): self.message = self.message() try: check = self.model.query.filter(self.field == field.data).first() except Exception as e: raise DatabaseAccessError(exception=e) if not check: if self.stop: raise StopValidation(self.message) else: raise ValidationError(self.message)
def __call__(self, form, field): if callable(self.message): self.message = self.message() try: data_as_int = int(field.data) if data_as_int < 0: raise Exception() except Exception: if self.stop: raise StopValidation(self.message) else: raise ValidationError(self.message)
def __call__(self, form, field): if callable(self.message): self.message = self.message() has_file_part = self.input_file_name in request.files current_file = request.files[self.input_file_name] valid_filename = current_file.filename != '' if (not has_file_part) or (not valid_filename): if self.stop: raise StopValidation(self.message) else: raise ValidationError(self.message)
def __call__(self, form, field): filename = getattr(field.data, 'name', '') if not filename: return filename = filename.lower() # testing with .endswith instead of the fastest `in` test, because # there may be extensions with more than one dot (.), e.g. ".tar.gz" if any(filename.endswith(ext) for ext in self.extensions): return raise StopValidation(self.message or field.gettext('File type does not allowed.'))
def __call__(self, form, field): if not field.data: return for d in field.data: if not isinstance(d, FileStorage): return if d.filename == '': return for f in form.data['photo']: filename = f.filename.lower() if isinstance(self.upload_set, abc.Iterable): if any(filename.endswith('.' + x) for x in self.upload_set): return raise StopValidation(self.message or field.gettext( 'File does not have an approved extension: {extensions}' ).format(extensions=', '.join(self.upload_set))) if not self.upload_set.file_allowed(field.data, filename): raise StopValidation( self.message or field.gettext('File does not have an approved extension.'))
def __call__(self, form, field): password = field.data.strip() if self.min_len < len(password) < self.max_len: lower = False upper = False digit = False for symbol in password: if symbol.islower() and not lower: lower = True elif symbol.isupper() and not upper: upper = True elif symbol.isdigit() and not digit: digit = True if lower and upper and digit: break if not lower or not upper: raise StopValidation( message= 'В пароле должны присутствоветь заглавные и строчные символы' ) if not digit: raise StopValidation( message='В пароле должны присутсвовать цифры') if lower and upper and digit: for count in range(len(password) - 2): keyboard_error = any( map( lambda keyboard_row: password[ count:count + 3].lower() in keyboard_row, PasswordValidate.keyboard_rows)) if keyboard_error: raise StopValidation( message= 'В пароле не должно быть 3 подряд идущих символов') else: raise StopValidation( message= f'Пароль должен быть от {self.min_len} до {self.max_len} символов' )
def __call__(self, form, field): result = verify_email(form.username.data.lower()) name = result.group(2) domain = Domain.query.filter_by(name=name).first() if self.message == None: message = field.gettext("This domain is unavailable.") else: message = self.message if domain == None: raise StopValidation(message)
def date_validator(form, field): message = ("Please, provide a valid date in the format YYYY-MM-DD, YYYY-MM" " or YYYY.") if field.data: for date_format in ["%Y-%m-%d", "%Y-%m", "%Y"]: try: datetime.strptime(field.data, date_format).date() except ValueError: pass else: break else: raise StopValidation(message)
def __call__(self, form, field): if field.data is None: # pragma: no cover raise ValidationError(get_message("EMAIL_NOT_PROVIDED")[0]) try: field.data = _security._mail_util.validate(field.data) except ValueError: msg = get_message("INVALID_EMAIL_ADDRESS")[0] # we stop further validators if email isn't valid. # TODO: email_validator provides some really nice error messages - however # they aren't localized. And there isn't an easy way to add multiple # errors at once. raise StopValidation(msg)
def year_validator(form, field): """Validate that the field contains an year in an acceptable range.""" hep = load_schema('hep') min_year = get_value( hep, 'properties.publication_info.items.properties.year.minimum') max_year = get_value( hep, 'properties.publication_info.items.properties.year.maximum') message = 'Please, provide an year between {} and {}.'.format( min_year, max_year) if field.data and not min_year <= int(field.data) <= max_year: raise StopValidation(message)
def validateUsername(self, form, field) -> bool(): """ \n@Returns True = Exists \n@Note: This will be part of the password's validation (chain both to avoid double flashes) """ # prove that username is not already taken (if taken != None & not taken == None) typedUsername = form.username.data # use generic 'form' variable usernameExists = self.isUsernameInUse(typedUsername) if not usernameExists: errMsg = f"Username '{typedUsername}' does not exist, try again" flash(errMsg) raise StopValidation(message=errMsg) else: return True
def __call__(self, form, field): if callable(self.message): self.message = self.message() current_file = request.files[self.input_file_name] filename = current_file.filename allowed_file = '.' in filename and filename.rsplit( '.', 1)[1] in self.allowed_extensions if not allowed_file: if self.stop: raise StopValidation(self.message) else: raise ValidationError(self.message)
def ORCIDValidator(form, field): """Validate that the given ORCID exists.""" msg = u"The ORCID iD was not found in <a href='http://orcid.org' target='_blank'>orcid.org</a>. Please, make sure it is valid." orcid_id = field.data if current_app.config.get("ORCID_APP_CREDENTIALS"): api = orcid.MemberAPI( current_app.config["ORCID_APP_CREDENTIALS"]["consumer_key"], current_app.config["ORCID_APP_CREDENTIALS"]["consumer_secret"]) try: result = api.search_member("orcid:" + orcid_id) if result['orcid-search-results']["num-found"] == 0: raise StopValidation(msg) except RequestException: return
def __call__(self, form, field): other_field = form._fields.get(self.other_field) if other_field is None: raise Exception('There is no field named "{}" in form'.format( self.other_field)) if bool(other_field.data) and (other_field.data == self.other_value): super(RequiredIf, self).__call__(form, field) elif bool(other_field.data) and not self.other_value: super(RequiredIf, self).__call__(form, field) else: raise StopValidation()
def __call__(self, form, field): try: other = form[self.fieldname] except KeyError: raise ValidationError( field.gettext("Invalid field name '%s'.") % self.fieldname) if other.data == '' or field.data == '': return elif field.data > other.data: message = self.message if message is None: message = field.gettext( 'Field must be less than %(other_name)s.') raise StopValidation(message)
def validate_data(form, field): notas = [] debitos = [] index = int(form.empresa.data) empresa_selected = form.empresa.choices[index][1] empresa = Empresa.query.filter_by(cnpj=empresa_selected[1]).first() indice = empresa.indice file = form.file_upload.data file.save('tmp/tmp.json') with open('tmp/tmp.json', 'r') as json_file: dados = json.load(json_file) validate_nota(dados) try: dados['cnpj'] except: raise StopValidation('Arquivo com chave CNPJ invalido') if empresa_selected[1] != dados['cnpj']: raise StopValidation("CNPJ das Empresas não conferem") #Executando o calculo do indice, das notas recebidas pelo aquivo json indice = calculo_nota_fiscal(notas, dados, empresa, indice) #Executando o calculo do indice, dos debitos recebidos pelo aquivo json indice = calculo_debito(debitos, dados, empresa, indice) empresa.indice = indice db.session.add_all(notas) db.session.add_all(debitos) db.session.add(empresa) db.session.commit()
def register_email_blacklist_validator(form, field): email_blacklist = app.config.get('EMAIL_BLACKLIST', []) email = field.data.strip() validation_exception = StopValidation('Blacklisted email provider') for item in email_blacklist: if isinstance(item, re.Pattern): if item.search(email): raise validation_exception elif isinstance(item, str): if item in email.lower(): raise validation_exception else: raise Exception('Unexpected email validator type {!r} ({!r})'.format(type(item), item)) return True
def __call__(self, form, field): if not (isinstance(field.data, FileStorage) and field.data): return file_size = len( field.data.read() ) / 1024 # read the file to determine its size and convert from bytes to Kb field.data.seek(0) # reset cursor position to beginning of file if file_size <= self.max_size: return else: # the file is too big => validation failure raise StopValidation( self.message or field.gettext('File should be smaller than ' + str(self.max_size) + ' Kb.'))