def import_validate_row(key, row, errors): # Fix birthday birthday = None if row['birthday']: try: birthday = datetime.strptime(row['birthday'], '%Y-%m-%d') except ValueError: import_report_error(errors, key, {'birthday': ['type']}) row['birthday'] = birthday # Clean iban and bic row['iban'] = row['iban'].upper().replace(" ", "").encode('ascii', 'ignore') row['bic'] = row['bic'].upper().replace(" ", "") if not validators.email(row['email']): import_report_error(errors, key, {'email': ['type']}) if row['iban'] != current_app.config.get( 'NO_IBAN_STRING', 'OUTSIDE_SEPA_AREA') and ( not validators.iban(row['iban']) or len(row['iban']) > 34): import_report_error(errors, key, {'iban': ['type']}) if row['bic'] and not (len(row['bic']) == 8 or len(row['bic']) == 11): import_report_error(errors, key, {'bic': ['type']}) for prop in ['name', 'address', 'city', 'email', 'iban']: if not row[prop].strip(): import_report_error(errors, key, {prop: ['nonblank']}) return (row, errors)
def validate_create_update_input(input, update=False): """ Validate input """ result = {} # Fetch & check account if not update: # Create only rid = get_rid(input['account']) account = Account.objects.filter(id=rid.id).first() result['account'] = account if not account: raise Exception(_('Invalid Account ID!')) if 'number' in input: system_setting_dude = SystemSettingDude() finance_bank_accounts_iban = system_setting_dude.get( 'finance_bank_accounts_iban') if finance_bank_accounts_iban == 'true': number = input['number'].strip() if not validators.iban(number): raise Exception(_('Number is not a valid IBAN!')) return result
def bankovni_racun(): ime_banke = Config.banka broj_racuna = Config.iban if not validators.iban(broj_racuna): broj_racuna = "Neispravan IBAN!" return render_template("bankAccount.html", banka=ime_banke, iban=broj_racuna)
def _is_iban(self, value): """ :param value: value to be validated as IBAN :return: Boolean ; True if IBAN ; False if not """ import validators valid_iban = True if not validators.iban(value): valid_iban = False return valid_iban
def main(ctx, iban: str, api_key: str, sandbox: bool, currency: str): """ \b ____ _ | __ ) _ _ __ _ _ _| |_ | _ \| | | |/ _` | | | | __| | |_) | |_| | (_| | |_| | |_ |____/ \__,_|\__,_|\__,_|\__| Buaut are several Bunq automations in a convenient CLI tool. Enable autocomplete for Bash (.bashrc): eval "$(_BUAUT_COMPLETE=source buaut)" Enable autocomplete for ZSH (.zshrc): eval "$(_BUAUT_COMPLETE=source_zsh buaut)" """ # Set Bunq context context = ApiEnvironmentType.SANDBOX if sandbox \ else ApiEnvironmentType.PRODUCTION # Setup Bunq authentication api_context = ApiContext.create(context, api_key, socket.gethostname()) api_context.ensure_session_active() # Load api context into BunqContext used for subsequent calls BunqContext.load_api_context(api_context) if validators.iban(iban): try: # Set monetary_account monetary_account: int = utils.get_monetary_account( value_type='IBAN', value=iban) except: # TODO: Exit nicely exit(1) else: # TODO: Exit nicely exit(1) # Append to ctx object to have available in commands ctx.obj = {} ctx.obj['args'] = {} ctx.obj['args']['iban'] = iban ctx.obj['args']['api_key'] = api_key ctx.obj['monetary_account'] = monetary_account ctx.obj['currency'] = currency
def convert_to_pointer(input: str) -> Pointer: """Convert input to Pointer Args: input (str): email, iban or phonenumber Returns: Pointer: converted input """ # Split since iban is passed as 'NL92BUNQ12445345,T Test' value = convert_comma_seperated_to_list(input) # Determine type and return if validators.email(value[0]): return Pointer(type_="EMAIL", value=value[0]) elif validators.iban(value[0]): return Pointer(type_="IBAN", value=value[0], name=value[1]) # TODO: implement phonenumber validation in validators elif value[0][1:].isdigit(): # removes + sign from phonenumber return Pointer(type_="PHONE_NUMBER", value=value[0]) else: # TODO: Create some logging class and exit with message print("No valid API Type") exit(1)
def import_validate_row(key, row, errors): # Fix birthday birthday = None if row['birthday']: try: birthday = datetime.strptime(row['birthday'], "%d-%m-%Y") except ValueError: import_report_error(errors,key,{'birthday': ['type']}) row['birthday'] = birthday # Clean iban and bic row['iban'] = row['iban'].upper().replace(" ", "").encode('ascii', 'ignore') row['bic'] = row['bic'].upper().replace(" ", "") if not validators.email(row['email']): import_report_error(errors,key,{'email': ['type']}) if not validators.iban(row['iban']) or len(row['iban']) > 34: import_report_error(errors,key,{'iban': ['type']}) if row['bic'] and not ( len(row['bic']) == 8 or len(row['bic']) == 11 ): import_report_error(errors,key,{'bic': ['type']}) for prop in ['name', 'address', 'city', 'email', 'iban']: if not row[prop].strip(): import_report_error(errors,key,{prop: ['nonblank']}) return (row, errors)
def test_returns_failed_validation_on_invalid_iban(value): result = validators.iban(value) assert isinstance(result, validators.ValidationFailure)
def test_returns_true_on_valid_iban(value): assert validators.iban(value)
def provjeri_iban(broj_racuna): if not validators.iban(broj_racuna): return False else: return True
def __init__(self, account=None, creditor=None, final_creditor=None, amount=None, currency='CHF', due_date=None, debtor=None, ref_number=None, extra_infos='', language='en'): # Account (IBAN) validation if not account: raise ValueError("The account parameter is mandatory") account = account.replace(' ', '') if account and len(account) != IBAN_CH_LENGTH: raise ValueError("IBAN must have exactly 21 characters") elif account and not validators.iban(account): raise ValueError("Sorry, the IBAN is not valid") self.account = account if amount is not None: m = re.match(AMOUNT_REGEX, amount) if not m: raise ValueError( "If provided, the amount must match the pattern '###.##'") self.amount = amount if currency not in self.allowed_currencies: raise ValueError("Currency can only contains: %s" % ", ".join(self.allowed_currencies)) self.currency = currency if due_date: m = re.match(DATE_REGEX, due_date) if not m: raise ValueError( "The date must match the pattern 'YYYY-MM-DD'") due_date = date(*[int(g) for g in m.groups()]) self.due_date = due_date if not creditor: raise ValueError("Creditor information is mandatory") try: self.creditor = Address(**creditor) except ValueError as err: raise ValueError("The creditor address is invalid: %s" % err) if final_creditor is not None: try: self.final_creditor = Address(**final_creditor) except ValueError as err: raise ValueError("The final creditor address is invalid: %s" % err) else: self.final_creditor = final_creditor if debtor is not None: try: self.debtor = Address(**debtor) except ValueError as err: raise ValueError("The debtor address is invalid: %s" % err) else: self.debtor = debtor if ref_number is None: self.ref_type = 'NON' elif len(ref_number) == 27: self.ref_type = 'QRR' else: self.ref_type = 'SCOR' self.ref_number = ref_number if len(extra_infos) > 140: raise ValueError( "Additional information cannot contain more than 140 characters" ) self.extra_infos = extra_infos if language not in ['en', 'de', 'fr', 'it']: raise ValueError("Language should be 'en', 'de', 'fr', or 'it'") self.language = language
def arg_validator(arg, vlist=None): """ 检查数据,可对同一个数据进行多种检查 arg : 字符串,要验证的参数 vlist : 列表,验证列表,每个元素包含两项. 第一个项是检查类型(字符串),第二项是可选参数字典,类似: [ ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}), ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}), ... ] 返回: 双元组,第一项为True 或 False,第二项为验证失败的类型(第一项为True的话第二项就留空) 注意: vlist 列表的第一项可以是字符串 "required",用于表示是必填项: 如果第一项不是,而且要验证的 arg 为空,会直接返回 True,不是的继续验证。 如果第一项是,就完全按照 vlist[1:] 的要求验证 vlist 的元素如果是验证整数/小数/email等不需要附加参数的可以直接传入验证类型字符串即可 用例(使用args_validator函数的,看这里vdict每个键值对的形式): vdict = { "token": ["required", "uuid"], "username": ["required", ("length", {"min": 4, "max": 30}), "safe_str"], "password": ["required", ("length", {"min": 4, "max": 20}), "safe_str"], "captcha": ["required", ("length", {"min": 4, "max": 8}), "safe_str"], } form = args_validator(self.request.arguments, vdict) """ if not any((isinstance(vlist, list), isinstance(vlist, tuple))): einfo = "不支持的数据类型!应使用列表或元组,但输入的是{}".format(type(vlist)) raise ValueError(einfo) if vlist[0] == "required": # 第一项不是 required 的,把第一项的 "required" 去掉 vlist = vlist[1:] else: # 第一项不是 required 的,如果 arg 是空的,直接返回 True,不是的继续验证 if not arg: return True, None # 待返回的验证结果 verification = None failed_type = None # 验证失败的类型 # 开始检查,有一个不通过就返回 False for i in vlist: local_verification = None if isinstance(i, str): # 如果是字符串的话就改为元组 i = (i, {}) if len(i) == 1: # 只有一个元素的,添加一个空字典 i = (i[0], {}) vtype = i[0] # 检查类型是第一项 vdict = i[1] # 检查类型所需的可选参数字典 # 在 validators 之外添加的 # 没有空白 if vtype == "no_space": if not re.search(r"\s", arg): local_verification = True # 安全字符串,只包含 0-9a-zA-Z-空格和下划线 elif vtype == "safe_str": if re.match(r"^[0-9a-zA-Z-_ ]+$", arg, flags=re.U): local_verification = True # 是否包含 elif vtype == "in": # 迭代 vdict 的键值(所以键名无所谓) for v in vdict.values(): if arg not in v: local_verification = False break elif vtype == "not_in": # 迭代 vdict 的键值(所以键名无所谓) for v in vdict.values(): if arg in v: local_verification = False break # 字符串形式的数字 elif vtype == "str_number": if re.match(r"[+-]?\d+$", arg, flags=re.U) or \ re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U): local_verification = True elif vtype == "str_int": if re.match(r"[+-]?\d+$", arg, flags=re.U): local_verification = True elif vtype == "str_float": if re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U): local_verification = True # 数字 elif vtype == "number": # 整数或浮点数都可以 local_verification = isinstance(arg, int) or isinstance(arg, float) elif vtype == "int": local_verification = isinstance(arg, int) elif vtype == "float": local_verification = isinstance(arg, float) # 直接调用 validators的 elif vtype == "length": local_verification = validators.length(arg, **vdict) elif vtype == "url": local_verification = validators.url(arg, **vdict) elif vtype == "email": local_verification = validators.email(arg, **vdict) elif vtype == "ip": # ipv4 或 ipv6都可以 local_verification = any((validators.ipv4(arg, **vdict), validators.ipv6(arg, **vdict))) elif vtype == "between": local_verification = validators.between(arg, **vdict) elif vtype == "uuid": local_verification = validators.uuid(arg, **vdict) elif vtype == "ipv4": local_verification = validators.ipv4(arg, **vdict) elif vtype == "ipv6": local_verification = validators.ipv6(arg, **vdict) elif vtype == "mac_address": local_verification = validators.mac_address(arg, **vdict) elif vtype == "iban": local_verification = validators.iban(arg, **vdict) elif vtype == "slug": local_verification = validators.slug(arg, **vdict) elif vtype == "truthy": local_verification = validators.truthy(arg, **vdict) # 对于验证不为真或没有验证的 # 不为真的时候返回的是: ValidationFailure(......) if not local_verification: verification = False failed_type = vtype break # 有一条不为 True, 直接返回 False else: verification = True # 处理返回值 if verification not in(False, True): verification = False if not verification: return verification, failed_type else: return True, None
def validate_iban(form, field): if field.raw_data[0] != current_app.config.get( 'NO_IBAN_STRING', 'OUTSIDE_SEPA_AREA') and (not iban( field.raw_data[0]) or len(field.raw_data[0]) > 34): raise validators.StopValidation('This is not a valid IBAN')
def validate_iban(form, field): if not iban(field.raw_data[0]) or len(field.raw_data[0]) > 34: raise validators.StopValidation('This is not a valid IBAN')