import re from datetime import datetime from app_common.const import USER_ID_REGEX def quarter_date_time(dt_format='%b %d, %Y'): def validate(value): try: value = datetime.strptime(value, dt_format) except ValueError: raise ValueError(f'The given string "{value}" does not conform to the date time format string "{dt_format}" ' f'(see: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).') return value return validate def regex_str(regex, error_msg=None): def validate(value): if not isinstance(value, str): raise ValueError('The given value is not a string.') if re.search(regex, value): return value exp_msg = error_msg or f'The given string does not match the expected regex (value="{value}", regex="{regex}").' raise ValueError(exp_msg) return validate def email(): email_regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$' return regex_str(email_regex, error_msg='The given value is not an email address.') def user_id(): def validate(value): if USER_ID_REGEX.fullmatch(value): return value raise ValueError(f'The given value is not a valid username (value="{value}").') return validate