diff --git a/pyvalidator/alpha.py b/pyvalidator/alpha.py index 1df268a..8d56776 100644 --- a/pyvalidator/alpha.py +++ b/pyvalidator/alpha.py @@ -23,15 +23,15 @@ 'sr-RS@latin': '^[A-ZČĆŽŠĐ]+$', 'sr-RS': '^[А-ЯЂЈЉЊЋЏ]+$', 'sv-SE': '^[A-ZÅÄÖ]+$', - 'th-TH': '^[ก-๐\s]+$', + 'th-TH': r'^[ก-๐\s]+$', 'tr-TR': '^[A-ZÇĞİıÖŞÜ]+$', 'uk-UA': '^[А-ЩЬЮЯЄIЇҐі]+$', 'vi-VN': '^[A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$', 'ku-IQ': '^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$', 'ar': '^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+', 'he': '^[א-ת]+', - 'fa': '^[\'آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی\']+$', - 'hi-IN': '^[\u0900-\u0961]+[\u0972-\u097F]*$', + 'fa': r'^[\'آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی\']+$', + 'hi-IN': r'^[\u0900-\u0961]+[\u0972-\u097F]*$', } alphanumeric = { @@ -58,15 +58,15 @@ 'sr-RS@latin': '^[0-9A-ZČĆŽŠĐ]+$', 'sr-RS': '^[0-9А-ЯЂЈЉЊЋЏ]+$', 'sv-SE': '^[0-9A-ZÅÄÖ]+$', - 'th-TH': '^[ก-๙\s]+$', + 'th-TH': r'^[ก-๙\s]+$', 'tr-TR': '^[0-9A-ZÇĞİıÖŞÜ]+$', 'uk-UA': '^[0-9А-ЩЬЮЯЄIЇҐі]+$', 'ku-IQ': '^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$', 'vi-VN': '^[0-9A-ZÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴĐÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]+$', 'ar': '^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+', 'he': '^[0-9א-ת]+', - 'fa': '^[\'0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰\']+$', - 'hi-IN': '^[\u0900-\u0963]+[\u0966-\u097F]*$', + 'fa': r'^[\'0-9آاءأؤئبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهةی۱۲۳۴۵۶۷۸۹۰\']+$', + 'hi-IN': r'^[\u0900-\u0963]+[\u0966-\u097F]*$', } decimal = { diff --git a/pyvalidator/is_alpha.py b/pyvalidator/is_alpha.py index 4f677f6..6cf7974 100644 --- a/pyvalidator/is_alpha.py +++ b/pyvalidator/is_alpha.py @@ -6,7 +6,7 @@ def is_alpha(input, locale='en-US', options={}): input = assert_string(input) - if locale == None: + if locale is None: locale = 'en-US' if 'ignore' in options and options['ignore']: @@ -16,13 +16,13 @@ def is_alpha(input, locale='en-US', options={}): input = input.sub(pattern, '') else: - raise Exception('ignore should be instance of a String or RegExp') + raise TypeError('ignore should be instance of a String or RegExp') if locale in alpha: pattern = RegEx(alpha[locale], 'i') return pattern.match(input) - raise Exception("Invalid locale {}".format(locale)) + raise ValueError("Invalid locale {}".format(locale)) locales = list(alpha.keys()) diff --git a/pyvalidator/is_ascii.py b/pyvalidator/is_ascii.py index 673ec38..2ec231b 100644 --- a/pyvalidator/is_ascii.py +++ b/pyvalidator/is_ascii.py @@ -3,6 +3,6 @@ def is_ascii(input: str) -> bool: - pattern = RegEx("^[\x00-\x7F]+$") + pattern = RegEx(r"^[\x00-\x7F]+$") input = assert_string(input) return pattern.match(input) diff --git a/pyvalidator/is_base64.py b/pyvalidator/is_base64.py index 448352f..da2fb48 100644 --- a/pyvalidator/is_base64.py +++ b/pyvalidator/is_base64.py @@ -11,8 +11,8 @@ def is_base64(input: str, options={}) -> bool: assert_string(input) - not_base64 = RegEx("[^A-Z0-9+\/=]", "i") - url_safe_base64 = RegEx("^[A-Z0-9_\-]*$", "i") + not_base64 = RegEx(r"[^A-Z0-9+/=]", "i") + url_safe_base64 = RegEx(r"^[A-Z0-9_\-]*$", "i") options = merge(options, default_base64_options) input_length = len(input) diff --git a/pyvalidator/is_byte_length.py b/pyvalidator/is_byte_length.py index cd8608e..32f9889 100644 --- a/pyvalidator/is_byte_length.py +++ b/pyvalidator/is_byte_length.py @@ -22,5 +22,5 @@ def is_byte_length(input: str, options={}) -> bool: input_length = len(split_input) - 1 return input_length >= options["min"] and ( - options["max"] == None or input_length <= options["max"] + options["max"] is None or input_length <= options["max"] ) diff --git a/pyvalidator/is_credit_card.py b/pyvalidator/is_credit_card.py index 57c2182..78324cb 100644 --- a/pyvalidator/is_credit_card.py +++ b/pyvalidator/is_credit_card.py @@ -6,19 +6,19 @@ def is_credit_card(input: str) -> bool: input = assert_string(input) - credit_card = RegEx("^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$") - sanetization_pattern = RegEx("[- ]+", 'g') + credit_card = RegEx(r"^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$") + sanitization_pattern = RegEx("[- ]+", 'g') - sanitized = input.sub(sanetization_pattern, '') + sanitized = input.sub(sanitization_pattern, '') if not credit_card.match(sanitized): return False - sum = 0 + _sum = 0 should_double = False - reversed_sanetized_input = sanitized[::-1] + reversed_sanitized_input = sanitized[::-1] - for digit in reversed_sanetized_input: + for digit in reversed_sanitized_input: if not is_number(digit): return False @@ -27,11 +27,11 @@ def is_credit_card(input: str) -> bool: if should_double: tmp_num = tmp_num * 2 if tmp_num >= 10: - sum += ((tmp_num % 10) + 1) + _sum += ((tmp_num % 10) + 1) else: - sum += tmp_num + _sum += tmp_num else: - sum += tmp_num + _sum += tmp_num should_double = not should_double - return bool(sanitized if (sum % 10) == 0 else False) + return bool(sanitized if (_sum % 10) == 0 else False) diff --git a/pyvalidator/is_currency.py b/pyvalidator/is_currency.py index 479335b..c936128 100644 --- a/pyvalidator/is_currency.py +++ b/pyvalidator/is_currency.py @@ -5,25 +5,25 @@ def currency_regex(options): - decimal_digits = "\d{" + str(options["digits_after_decimal"][0]) + "}" + decimal_digits = r"\d{" + str(options["digits_after_decimal"][0]) + "}" for index, digit in enumerate(options["digits_after_decimal"]): if index != 0: - decimal_digits = "{}|\d{}{}{}".format(decimal_digits, '{', digit, '}') + decimal_digits = r"{}|\d{}{}{}".format(decimal_digits, '{', digit, '}') def __match(x): return "\\{}".format(x.group(0)) - symbol = "({}){}".format(RegEx.sub("\W", __match, options["symbol"]), '' if options["require_symbol"] else '?') + symbol = "({}){}".format(RegEx.sub(r"\W", __match, options["symbol"]), '' if options["require_symbol"] else '?') negative = '-?' - whole_dollar_amount_without_sep = '[1-9]\d*' - whole_dollar_amount_with_sep = "[1-9]\d{{0,2}}({}\d{{3}})*".format(options["thousands_separator"]) + whole_dollar_amount_without_sep = r'[1-9]\d*' + whole_dollar_amount_with_sep = r"[1-9]\d{{0,2}}({}\d{{3}})*".format(options["thousands_separator"]) valid_whole_dollar_amounts = [ '0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep ] whole_dollar_amount = "({})?".format(join(valid_whole_dollar_amounts, '|')) - decimal_amount = "(\{}({})){}".format(options["decimal_separator"], decimal_digits, '' if options["require_decimal"] else '?') + decimal_amount = r"(\{}({})){}".format(options["decimal_separator"], decimal_digits, '' if options["require_decimal"] else '?') pattern = "{}{}".format( whole_dollar_amount, decimal_amount if (options["allow_decimal"] or options["require_decimal"]) else '' @@ -36,7 +36,7 @@ def __match(x): pattern = negative + pattern if options["allow_negative_sign_placeholder"]: - pattern = "( (?!\-))?" + pattern + pattern = r"( (?!\-))?" + pattern elif options["allow_space_after_symbol"]: pattern = " ?" + pattern elif options["allow_space_after_digits"]: @@ -53,7 +53,7 @@ def __match(x): elif not (options["negative_sign_before_digits"] and options["negative_sign_after_digits"]): pattern = negative + pattern - return RegEx("^(?!-? )(?=.*\d){}$".format(pattern)) + return RegEx(r"^(?!-? )(?=.*\d){}$".format(pattern)) default_currency_options = { diff --git a/pyvalidator/is_data_uri.py b/pyvalidator/is_data_uri.py index 9832532..5268ac6 100644 --- a/pyvalidator/is_data_uri.py +++ b/pyvalidator/is_data_uri.py @@ -5,9 +5,9 @@ def is_data_uri(input: str) -> bool: assert_string(input) - valid_media_type = RegEx("^[a-z]+\/[a-z0-9\-\+]+$", 'i') - valid_attribute = RegEx("^[a-z\-]+=[a-z0-9\-]+$", 'i') - valid_data = RegEx("^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$", 'i') + valid_media_type = RegEx(r"^[a-z]+/[a-z0-9\-\+]+$", 'i') + valid_attribute = RegEx(r"^[a-z\-]+=[a-z0-9\-]+$", 'i') + valid_data = RegEx(r"^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@/\?%\s]*$", 'i') data = input.split(',') diff --git a/pyvalidator/is_date.py b/pyvalidator/is_date.py index 11afb1a..3f8c762 100644 --- a/pyvalidator/is_date.py +++ b/pyvalidator/is_date.py @@ -60,14 +60,14 @@ def zip(date_list: ListT[str], format_list: ListT[str]) -> ListT[Tuple[str, str] def is_date(input: str, options: IsDateOptions = {}) -> bool: input = assert_string(input) - date_format_pattern = RegEx(r"(^(y{4}|y{2})[|:;,.\/-](m{1,2})[|:;,.\/-](d{1,2})$)|(^(m{1,2})[|:;,.\/-](d{1,2})[|:;,.\/-]((y{4}|y{2})$))|(^(d{1,2})[|:;,.\/-](m{1,2})[|:;,.\/-]((y{4}|y{2})$))", 'i') + date_format_pattern = RegEx(r"(^(y{4}|y{2})[|:;,./-](m{1,2})[|:;,./-](d{1,2})$)|(^(m{1,2})[|:;,./-](d{1,2})[|:;,./-]((y{4}|y{2})$))|(^(d{1,2})[|:;,./-](m{1,2})[|:;,./-]((y{4}|y{2})$))", 'i') options = merge(options, __default_options) format = String(options['format']) if not date_format_pattern.match(format): - raise Exception('Not supported format provided: ', format) + raise ValueError('Not supported format provided: ', format) format_delimiter: Union[str, None] = List(options['delimiters']).find(lambda delimiter, _: delimiter in format) @@ -80,20 +80,20 @@ def is_date(input: str, options: IsDateOptions = {}) -> bool: if not input_delimiter: return False - format = format if options['strict_mode'] else format.sub("\{}".format(input_delimiter), '/') - input = input if options['strict_mode'] else input.sub("\{}".format(input_delimiter), '/') + format = format if options['strict_mode'] else format.sub(r"\{}".format(input_delimiter), '/') + input = input if options['strict_mode'] else input.sub(r"\{}".format(input_delimiter), '/') - format_tupples = zip( + format_tuples = zip( input.split(date_delimiter), format.lower().split(date_delimiter) ) date_dict = {} - for format_tupple in format_tupples: - if len(format_tupple[0]) != len(format_tupple[1]): + for format_tuple in format_tuples: + if len(format_tuple[0]) != len(format_tuple[1]): return False - format_char = format_tupple[1][0] - date_dict[format_char] = format_tupple[0] + format_char = format_tuple[1][0] + date_dict[format_char] = format_tuple[0] return bool(to_date("{}/{}/{}".format(date_dict['m'], date_dict['d'], date_dict['y']))) diff --git a/pyvalidator/is_decimal.py b/pyvalidator/is_decimal.py index 2d35a30..126f78a 100644 --- a/pyvalidator/is_decimal.py +++ b/pyvalidator/is_decimal.py @@ -10,7 +10,7 @@ def decimal_regexp(options): local_decimal = decimal[local] decimal_digits = options["decimal_digits"] require_decimal = '' if options["force_decimal"] else '?' - regex = "^[-+]?([0-9]+)?(\{}[0-9]{{".format(local_decimal) + "{}}}){}$".format(decimal_digits, require_decimal) + regex = r"^[-+]?([0-9]+)?(\{}[0-9]{{".format(local_decimal) + "{}}}){}$".format(decimal_digits, require_decimal) return RegEx(regex) @@ -31,7 +31,7 @@ def is_decimal(input: str, options={}) -> bool: options = merge(options, default_decimal_options) if options["locale"] not in decimal: - raise Exception("Invalid locale '{}'".format(options["locale"])) + raise ValueError("Invalid locale '{}'".format(options["locale"])) without_white_space = input.sub(" ", '') return includesNot(blacklist, without_white_space) and bool(decimal_regexp(options).match(input)) diff --git a/pyvalidator/is_divisible_by.py b/pyvalidator/is_divisible_by.py index 2a36d10..3bdc732 100644 --- a/pyvalidator/is_divisible_by.py +++ b/pyvalidator/is_divisible_by.py @@ -7,6 +7,6 @@ def is_divisible_by(input: str, num: Union[int, float, str]) -> bool: assert_string(input) - if to_float(input) != None and to_int(num) != None: + if to_float(input) is not None and to_int(num) is not None: return (to_float(input) % to_int(num)) == 0 return False diff --git a/pyvalidator/is_ean.py b/pyvalidator/is_ean.py index 8105c06..9bdcda5 100644 --- a/pyvalidator/is_ean.py +++ b/pyvalidator/is_ean.py @@ -32,7 +32,7 @@ def reducer(acc, partial_sum): def is_ean(input: str) -> bool: input = assert_string(input) - valid_ean_regex = RegEx("^(\d{8}|\d{13}|\d{14})$") + valid_ean_regex = RegEx(r"^(\d{8}|\d{13}|\d{14})$") actual_check_digit = input.slice(-1) if not is_number(actual_check_digit): diff --git a/pyvalidator/is_email.py b/pyvalidator/is_email.py index 78c3c8c..3bece86 100644 --- a/pyvalidator/is_email.py +++ b/pyvalidator/is_email.py @@ -1,4 +1,4 @@ -from typing import TypedDict +from typing import TypedDict, Union from .is_byte_length import is_byte_length from .is_fqdn import is_fqdn @@ -20,7 +20,7 @@ class IsEmailOptions(TypedDict): domain_specific_validation: bool allow_ip_domain: bool blacklisted_chars: str - host_blacklist: List + host_blacklist: Union[List, list] default_email_options: IsEmailOptions = { @@ -67,15 +67,15 @@ def is_email(input: str, options: IsEmailOptions = {}) -> bool: options = merge(options, default_email_options) split_name_address = r"^([^\x00-\x1F\x7F-\x9F]+)<" - email_user_part = r"^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$" + email_user_part = r"^[a-z\d!#\$%&'\*\+\-/=\?\^_`{\|}~]+$" gmail_user_part = r"^[a-z\d]+$" quoted_email_user = r"^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$" - email_user_utf8_part = r"^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$" + email_user_utf8_part = r"^[a-z\d!#\$%&'\*\+\-/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$" quoted_email_user_utf8 = r"^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$" default_max_email_length = 254 if options["require_display_name"] or options["allow_display_name"]: - display_email = input.findMatches(split_name_address, 'i') + display_email = input.find_matches(split_name_address, 'i') if display_email: display_name = String(display_email[0]) @@ -105,7 +105,7 @@ def is_email(input: str, options: IsEmailOptions = {}) -> bool: user = user.lower() username = String(user.split('+')[0]) - if not is_byte_length(username.sub(RegEx('\.', 'g'), ''), {"min": 6, "max": 30}): + if not is_byte_length(username.sub(RegEx(r'\.', 'g'), ''), {"min": 6, "max": 30}): return False user_parts = username.split('.') @@ -149,7 +149,7 @@ def is_email(input: str, options: IsEmailOptions = {}) -> bool: return False if options["blacklisted_chars"]: - if user.findMatches(RegEx("[" + options["blacklisted_chars"] + "]+", 'g')): + if user.find_matches(RegEx("[" + options["blacklisted_chars"] + "]+", 'g')): return False return True diff --git a/pyvalidator/is_emoji.py b/pyvalidator/is_emoji.py index 7da1c95..fb79e97 100644 --- a/pyvalidator/is_emoji.py +++ b/pyvalidator/is_emoji.py @@ -4,19 +4,19 @@ from .utils.assert_string import assert_string from .utils.merge import merge -empji_patterns = ( +emoji_patterns = ( "^[" - "\U0001F1E0-\U0001F1FF" # flags (iOS) - "\U0001F300-\U0001F5FF" # symbols & pictographs - "\U0001F600-\U0001F64F" # emoticons - "\U0001F680-\U0001F6FF" # transport & map symbols - "\U0001F700-\U0001F77F" # alchemical symbols - "\U0001F780-\U0001F7FF" # Geometric Shapes Extended - "\U0001F800-\U0001F8FF" # Supplemental Arrows-C - "\U0001F900-\U0001F9FF" # Supplemental Symbols and Pictographs - "\U0001FA00-\U0001FA6F" # Chess Symbols - "\U0001FA70-\U0001FAFF" # Symbols and Pictographs Extended-A - "\U00002702-\U000027B0" # Dingbats + r"\U0001F1E0-\U0001F1FF" # flags (iOS) + r"\U0001F300-\U0001F5FF" # symbols & pictographs + r"\U0001F600-\U0001F64F" # emoticons + r"\U0001F680-\U0001F6FF" # transport & map symbols + r"\U0001F700-\U0001F77F" # alchemical symbols + r"\U0001F780-\U0001F7FF" # Geometric Shapes Extended + r"\U0001F800-\U0001F8FF" # Supplemental Arrows-C + r"\U0001F900-\U0001F9FF" # Supplemental Symbols and Pictographs + r"\U0001FA00-\U0001FA6F" # Chess Symbols + r"\U0001FA70-\U0001FAFF" # Symbols and Pictographs Extended-A + r"\U00002702-\U000027B0" # Dingbats "]$" ) @@ -37,17 +37,17 @@ def is_emoji(input: str, options: IsEmojiOptions = {}) -> bool: def is_flag_emoji(c): return ( - "\U0001F1E6\U0001F1E8" <= c <= "\U0001F1FF\U0001F1FC" + r"\U0001F1E6\U0001F1E8" <= c <= r"\U0001F1FF\U0001F1FC" or ( c in [ - "\U0001F3F4\U000e0067\U000e0062\U000e0065\U000e006e\U000e0067\U000e007f", - "\U0001F3F4\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f", - "\U0001F3F4\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f" + r"\U0001F3F4\U000e0067\U000e0062\U000e0065\U000e006e\U000e0067\U000e007f", + r"\U0001F3F4\U000e0067\U000e0062\U000e0073\U000e0063\U000e0074\U000e007f", + r"\U0001F3F4\U000e0067\U000e0062\U000e0077\U000e006c\U000e0073\U000e007f" ] ) ) - if options["omit_rule"] != None: + if options["omit_rule"] is not None: input = input.sub(options["omit_rule"], '') if not input.length: @@ -55,7 +55,7 @@ def is_flag_emoji(c): for char in input: char = String(char) - if not (char.match(empji_patterns) or is_flag_emoji(char)): + if not (char.match(emoji_patterns) or is_flag_emoji(char)): return False return True diff --git a/pyvalidator/is_even.py b/pyvalidator/is_even.py index be47be4..6966005 100644 --- a/pyvalidator/is_even.py +++ b/pyvalidator/is_even.py @@ -6,7 +6,7 @@ def is_even(input: Union[int, str]) -> bool: input = to_int(input) - if input == None: + if input is None: return False return not bool(input % 2) diff --git a/pyvalidator/is_float.py b/pyvalidator/is_float.py index 688b30e..507c577 100644 --- a/pyvalidator/is_float.py +++ b/pyvalidator/is_float.py @@ -2,7 +2,7 @@ from .utils.Classes.RegEx import RegEx from .utils.assert_string import assert_string from .utils.includes import includes -from .utils.math import grather_then_check, less_then_check +from .utils.math import gather_then_check, less_then_check from .utils.merge import merge __default_options = { @@ -22,15 +22,15 @@ def is_float(input: str, options=__default_options) -> bool: if includes(['+', '-', '.', ''], input): return False - float_pattern = RegEx("^(?:[-+])?(?:[0-9]+)?(?:\{}[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$".format(decimal[options["locale"]] if bool(options["locale"]) else '.')) + float_pattern = RegEx(r"^(?:[-+])?(?:[0-9]+)?(?:\{}[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$".format(decimal[options["locale"]] if bool(options["locale"]) else '.')) transformed_input = input.sub(',', '.').sub('٫', '.') is_valid = float_pattern.match(input) - min_valid = grather_then_check(transformed_input, options["min"]) + min_valid = gather_then_check(transformed_input, options["min"]) max_valid = less_then_check(transformed_input, options["max"]) - gt_valid = grather_then_check(transformed_input, options["gt"]) + gt_valid = gather_then_check(transformed_input, options["gt"]) lt_valid = less_then_check(transformed_input, options["lt"]) return is_valid and min_valid and max_valid and lt_valid and gt_valid diff --git a/pyvalidator/is_fqdn.py b/pyvalidator/is_fqdn.py index dcac55b..9b4ff3a 100644 --- a/pyvalidator/is_fqdn.py +++ b/pyvalidator/is_fqdn.py @@ -39,13 +39,13 @@ def is_fqdn(input: str, options: IsFqdnOptions = {}) -> bool: if options["require_tld"]: if parts.length < 2: return False - if not tld.match(RegEx("^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$", 'i')): + if not tld.match(RegEx(r"^([a-z\u00A1-\u00A8\u00AA-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}|xn[a-z0-9-]{2,})$", 'i')): return False - if RegEx('\s').findall(tld): + if RegEx(r'\s').findall(tld): return False - if not options["allow_numeric_tld"] and tld.match("^\d+$"): + if not options["allow_numeric_tld"] and tld.match(r"^\d+$"): return False for part in parts: diff --git a/pyvalidator/is_full_width.py b/pyvalidator/is_full_width.py index e07a5e3..621a178 100644 --- a/pyvalidator/is_full_width.py +++ b/pyvalidator/is_full_width.py @@ -5,6 +5,6 @@ def is_full_width(input: str) -> bool: input = assert_string(input) - full_width_pattern = RegEx("[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]") + full_width_pattern = RegEx(r"[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]") return full_width_pattern.match(input) diff --git a/pyvalidator/is_hsl.py b/pyvalidator/is_hsl.py index 66b3258..86cecb2 100644 --- a/pyvalidator/is_hsl.py +++ b/pyvalidator/is_hsl.py @@ -10,7 +10,7 @@ def is_hsl(input: str) -> bool: 'i' ) hsl_space = RegEx( - r"^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(\s(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}\s?(\/\s((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?)\s?)?\)$", + r"^hsla?\(((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?))(deg|grad|rad|turn)?(\s(\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%){2}\s?(/\s((\+|\-)?([0-9]+(\.[0-9]+)?(e(\+|\-)?[0-9]+)?|\.[0-9]+(e(\+|\-)?[0-9]+)?)%?)\s?)?\)$", 'i' ) diff --git a/pyvalidator/is_html_element.py b/pyvalidator/is_html_element.py index c4cfde9..d0aa81a 100644 --- a/pyvalidator/is_html_element.py +++ b/pyvalidator/is_html_element.py @@ -20,6 +20,6 @@ def is_html_element(input: str, options: IsHtmlElementOptions = default_email_op if options["contains"]: index = input.search(html_contains_pattern) - return True if index != None else False + return True if index is not None else False return input.match(html_strict) diff --git a/pyvalidator/is_iban.py b/pyvalidator/is_iban.py index 474d5b6..9e8be02 100644 --- a/pyvalidator/is_iban.py +++ b/pyvalidator/is_iban.py @@ -13,82 +13,82 @@ class IsIbanOptions(TypedDict): } iban_patterns = { - "AD": "^AD\\d{10}[A-Z0-9]{12}$", - "AE": "^AE\\d{21}$", - "AL": "^AL\\d{10}[A-Z0-9]{16}$", - "AT": "^AT\\d{18}$", - "AZ": "^AZ\\d{2}[A-Z]{4}[A-Z0-9]{20}$", - "BA": "^BA\\d{18}$", - "BE": "^BE\\d{14}$", - "BG": "^BG\\d{2}[A-Z]{4}\\d{6}[A-Z0-9]{8}$", - "BH": "^BH\\d{2}[A-Z]{4}[A-Z0-9]{14}$", - "BR": "^BR\\d{25}[A-Z]{1}[A-Z0-9]{1}$", - "BY": "^BY\\d{2}[A-Z0-9]{4}\\d{4}[A-Z0-9]{16}$", - "CH": "^CH\\d{7}[A-Z0-9]{12}$", - "CR": "^CR\\d{20}$", - "CY": "^CY\\d{10}[A-Z0-9]{16}$", - "CZ": "^CZ\\d{22}$", - "DE": "^DE\\d{20}$", - "DK": "^DK\\d{16}$", - "DO": "^DO\\d{2}[A-Z0-9]{4}\\d{20}$", - "EE": "^EE\\d{18}$", - "EG": "^EG\\d{27}$", - "ES": "^ES\\d{22}$", - "FI": "^FI\\d{16}$", - "FO": "^FO\\d{16}$", - "FR": "^FR\\d{12}[A-Z0-9]{11}\\d{2}$", - "GB": "^GB\\d{2}[A-Z]{4}\\d{14}$", - "GE": "^GE\\d{2}[A-Z]{2}\\d{16}$", - "GI": "^GI\\d{2}[A-Z]{4}[A-Z0-9]{15}$", - "GL": "^GL\\d{16}$", - "GR": "^GR\\d{9}[A-Z0-9]{16}$", - "GT": "^GT\\d{2}[A-Z0-9]{24}$", - "HR": "^HR\\d{19}$", - "HU": "^HU\\d{26}$", - "IE": "^IE\\d{2}[A-Z]{4}\\d{14}$", - "IL": "^IL\\d{21}$", - "IQ": "^IQ\\d{2}[A-Z]{4}\\d{15}$", - "IS": "^IS\\d{24}$", - "IT": "^IT\\d{2}[A-Z]{1}\\d{10}[A-Z0-9]{12}$", - "JO": "^JO\\d{2}[A-Z]{4}\\d{4}[A-Z0-9]{18}$", - "KW": "^KW\\d{2}[A-Z]{4}[A-Z0-9]{22}$", - "KZ": "^KZ\\d{5}[A-Z0-9]{13}$", - "LB": "^LB\\d{6}[A-Z0-9]{20}$", - "LC": "^LC\\d{2}[A-Z]{4}[A-Z0-9]{24}$", - "LI": "^LI\\d{7}[A-Z0-9]{12}$", - "LT": "^LT\\d{18}$", - "LU": "^LU\\d{5}[A-Z0-9]{13}$", - "LV": "^LV\\d{2}[A-Z]{4}[A-Z0-9]{13}$", - "MC": "^MC\\d{12}[A-Z0-9]{11}\\d{2}$", - "MD": "^MD\\d{2}[A-Z0-9]{20}$", - "ME": "^ME\\d{20}$", - "MK": "^MK\\d{5}[A-Z0-9]{10}\\d{2}$", - "MR": "^MR\\d{25}$", - "MT": "^MT\\d{2}[A-Z]{4}\\d{5}[A-Z0-9]{18}$", - "MU": "^MU\\d{2}[A-Z]{4}\\d{19}[A-Z]{3}$", - "NL": "^NL\\d{2}[A-Z]{4}\\d{10}$", - "NO": "^NO\\d{13}$", - "PK": "^PK\\d{2}[A-Z]{4}[A-Z0-9]{16}$", - "PL": "^PL\\d{26}$", - "PS": "^PS\\d{2}[A-Z]{4}[A-Z0-9]{21}$", - "PT": "^PT\\d{23}$", - "QA": "^QA\\d{2}[A-Z]{4}[A-Z0-9]{21}$", - "RO": "^RO\\d{2}[A-Z]{4}[A-Z0-9]{16}$", - "RS": "^RS\\d{20}$", - "SA": "^SA\\d{4}[A-Z0-9]{18}$", - "SC": "^SC\\d{2}[A-Z]{4}\\d{20}[A-Z]{3}$", - "SE": "^SE\\d{22}$", - "SI": "^SI\\d{17}$", - "SK": "^SK\\d{22}$", - "SM": "^SM\\d{2}[A-Z]{1}\\d{10}[A-Z0-9]{12}$", - "ST": "^ST\\d{23}$", - "SV": "^SV\\d{2}[A-Z]{4}\\d{20}$", - "TL": "^TL\\d{21}$", - "TN": "^TN\\d{22}$", - "TR": "^TR\\d{8}[A-Z0-9]{16}$", - "UA": "^UA\\d{8}[A-Z0-9]{19}$", - "VA": "^VA\\d{20}$", - "VG": "^VG\\d{2}[A-Z]{4}\\d{16}$", + "AD": r"^AD\d{10}[A-Z0-9]{12}$", + "AE": r"^AE\d{21}$", + "AL": r"^AL\d{10}[A-Z0-9]{16}$", + "AT": r"^AT\d{18}$", + "AZ": r"^AZ\d{2}[A-Z]{4}[A-Z0-9]{20}$", + "BA": r"^BA\d{18}$", + "BE": r"^BE\d{14}$", + "BG": r"^BG\d{2}[A-Z]{4}\d{6}[A-Z0-9]{8}$", + "BH": r"^BH\d{2}[A-Z]{4}[A-Z0-9]{14}$", + "BR": r"^BR\d{25}[A-Z]{1}[A-Z0-9]{1}$", + "BY": r"^BY\d{2}[A-Z0-9]{4}\d{4}[A-Z0-9]{16}$", + "CH": r"^CH\d{7}[A-Z0-9]{12}$", + "CR": r"^CR\d{20}$", + "CY": r"^CY\d{10}[A-Z0-9]{16}$", + "CZ": r"^CZ\d{22}$", + "DE": r"^DE\d{20}$", + "DK": r"^DK\d{16}$", + "DO": r"^DO\d{2}[A-Z0-9]{4}\d{20}$", + "EE": r"^EE\d{18}$", + "EG": r"^EG\d{27}$", + "ES": r"^ES\d{22}$", + "FI": r"^FI\d{16}$", + "FO": r"^FO\d{16}$", + "FR": r"^FR\d{12}[A-Z0-9]{11}\d{2}$", + "GB": r"^GB\d{2}[A-Z]{4}\d{14}$", + "GE": r"^GE\d{2}[A-Z]{2}\d{16}$", + "GI": r"^GI\d{2}[A-Z]{4}[A-Z0-9]{15}$", + "GL": r"^GL\d{16}$", + "GR": r"^GR\d{9}[A-Z0-9]{16}$", + "GT": r"^GT\d{2}[A-Z0-9]{24}$", + "HR": r"^HR\d{19}$", + "HU": r"^HU\d{26}$", + "IE": r"^IE\d{2}[A-Z]{4}\d{14}$", + "IL": r"^IL\d{21}$", + "IQ": r"^IQ\d{2}[A-Z]{4}\d{15}$", + "IS": r"^IS\d{24}$", + "IT": r"^IT\d{2}[A-Z]{1}\d{10}[A-Z0-9]{12}$", + "JO": r"^JO\d{2}[A-Z]{4}\d{4}[A-Z0-9]{18}$", + "KW": r"^KW\d{2}[A-Z]{4}[A-Z0-9]{22}$", + "KZ": r"^KZ\d{5}[A-Z0-9]{13}$", + "LB": r"^LB\d{6}[A-Z0-9]{20}$", + "LC": r"^LC\d{2}[A-Z]{4}[A-Z0-9]{24}$", + "LI": r"^LI\d{7}[A-Z0-9]{12}$", + "LT": r"^LT\d{18}$", + "LU": r"^LU\d{5}[A-Z0-9]{13}$", + "LV": r"^LV\d{2}[A-Z]{4}[A-Z0-9]{13}$", + "MC": r"^MC\d{12}[A-Z0-9]{11}\d{2}$", + "MD": r"^MD\d{2}[A-Z0-9]{20}$", + "ME": r"^ME\d{20}$", + "MK": r"^MK\d{5}[A-Z0-9]{10}\d{2}$", + "MR": r"^MR\d{25}$", + "MT": r"^MT\d{2}[A-Z]{4}\d{5}[A-Z0-9]{18}$", + "MU": r"^MU\d{2}[A-Z]{4}\d{19}[A-Z]{3}$", + "NL": r"^NL\d{2}[A-Z]{4}\d{10}$", + "NO": r"^NO\d{13}$", + "PK": r"^PK\d{2}[A-Z]{4}[A-Z0-9]{16}$", + "PL": r"^PL\d{26}$", + "PS": r"^PS\d{2}[A-Z]{4}[A-Z0-9]{21}$", + "PT": r"^PT\d{23}$", + "QA": r"^QA\d{2}[A-Z]{4}[A-Z0-9]{21}$", + "RO": r"^RO\d{2}[A-Z]{4}[A-Z0-9]{16}$", + "RS": r"^RS\d{20}$", + "SA": r"^SA\d{4}[A-Z0-9]{18}$", + "SC": r"^SC\d{2}[A-Z]{4}\d{20}[A-Z]{3}$", + "SE": r"^SE\d{22}$", + "SI": r"^SI\d{17}$", + "SK": r"^SK\d{22}$", + "SM": r"^SM\d{2}[A-Z]{1}\d{10}[A-Z0-9]{12}$", + "ST": r"^ST\d{23}$", + "SV": r"^SV\d{2}[A-Z]{4}\d{20}$", + "TL": r"^TL\d{21}$", + "TN": r"^TN\d{22}$", + "TR": r"^TR\d{8}[A-Z0-9]{16}$", + "UA": r"^UA\d{8}[A-Z0-9]{19}$", + "VA": r"^VA\d{20}$", + "VG": r"^VG\d{2}[A-Z]{4}\d{16}$", } diff --git a/pyvalidator/is_imei.py b/pyvalidator/is_imei.py index d98ee92..4bba048 100644 --- a/pyvalidator/is_imei.py +++ b/pyvalidator/is_imei.py @@ -18,10 +18,10 @@ def is_imei(input: str, options={}) -> bool: input = assert_string(input) options = merge(options, default_email_options) - imei_regex_without_hypens = r"^[0-9]{15}$" - imei_regex_with_hypens = r"^\d{2}-\d{6}-\d{6}-\d{1}$" + imei_regex_without_hyphens = r"^[0-9]{15}$" + imei_regex_with_hyphens = r"^\d{2}-\d{6}-\d{6}-\d{1}$" - imei_regex = imei_regex_with_hypens if options["allow_hyphens"] else imei_regex_without_hypens + imei_regex = imei_regex_with_hyphens if options["allow_hyphens"] else imei_regex_without_hyphens if not input.match(imei_regex): return False diff --git a/pyvalidator/is_int.py b/pyvalidator/is_int.py index 120bae4..aecf728 100644 --- a/pyvalidator/is_int.py +++ b/pyvalidator/is_int.py @@ -1,6 +1,6 @@ from .utils.Classes.RegEx import RegEx from .utils.assert_string import assert_string -from .utils.math import grather_then_check, less_then_check +from .utils.math import gather_then_check, less_then_check from .utils.merge import merge __default_options = { @@ -26,9 +26,9 @@ def is_int(input: str, options=__default_options) -> bool: input_valid = bool(picked_regex.match(input)) - min_check_passed = grather_then_check(input, options["min"]) + min_check_passed = gather_then_check(input, options["min"]) max_check_passed = less_then_check(input, options["max"]) - lt_check_passed = grather_then_check(input, options["lt"]) + lt_check_passed = gather_then_check(input, options["lt"]) gt_check_passed = less_then_check(input, options["gt"]) return input_valid and min_check_passed and max_check_passed and lt_check_passed and gt_check_passed diff --git a/pyvalidator/is_ip.py b/pyvalidator/is_ip.py index 6aac951..7e0d7d5 100644 --- a/pyvalidator/is_ip.py +++ b/pyvalidator/is_ip.py @@ -38,7 +38,7 @@ def is_ip(input: str, version: Literal[4, 6, '4', '6', None] = None) -> bool: ip_v4_address_pattern = RegEx('^' + ip_v4_address + '$') ip_v6_address_pattern = RegEx(ip_v6_address) - if version == None: + if version is None: return is_ip(input, 4) or is_ip(input, 6) if includesNot(ip_versions, version): diff --git a/pyvalidator/is_ip_range.py b/pyvalidator/is_ip_range.py index 4974114..c2e9da6 100644 --- a/pyvalidator/is_ip_range.py +++ b/pyvalidator/is_ip_range.py @@ -4,7 +4,7 @@ from .utils.Classes.String import String from .utils.assert_string import assert_string -subnet_maybe = "^\d{1,3}$" +subnet_maybe = r"^\d{1,3}$" subnet_v4 = 32 subnet_v6 = 128 diff --git a/pyvalidator/is_isrc.py b/pyvalidator/is_isrc.py index 8fbcfe8..d4db3aa 100644 --- a/pyvalidator/is_isrc.py +++ b/pyvalidator/is_isrc.py @@ -5,6 +5,6 @@ def is_isrc(input: str) -> bool: input = assert_string(input) - isrc_pattern = RegEx("^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$") + isrc_pattern = RegEx(r"^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$") return isrc_pattern.match(input) diff --git a/pyvalidator/is_json.py b/pyvalidator/is_json.py index cf1e946..299a8ce 100644 --- a/pyvalidator/is_json.py +++ b/pyvalidator/is_json.py @@ -7,7 +7,7 @@ class IsJsonOptions(TypedDict): - allow_primitives: str + allow_primitives: bool default_json_options: IsJsonOptions = { diff --git a/pyvalidator/is_mobile_number.py b/pyvalidator/is_mobile_number.py index e2eb98e..1cbefaa 100644 --- a/pyvalidator/is_mobile_number.py +++ b/pyvalidator/is_mobile_number.py @@ -1,13 +1,9 @@ -from typing import List, Literal, Tuple, TypedDict +from typing import List, Literal, Tuple from .utils.assert_string import assert_string from .utils.merge import merge -class IsMobileNumberOptions(TypedDict): - strict_mode: bool - - Locals = Literal[ 'am-AM', 'ar-AE', @@ -243,7 +239,7 @@ class IsMobileNumberOptions(TypedDict): 'pt-BR': r'^((\+?55\ ?[1-9]{2}\ ?)|(\+?55\ ?\([1-9]{2}\)\ ?)|(0[1-9]{2}\ ?)|(\([1-9]{2}\)\ ?)|([1-9]{2}\ ?))((\d{4}\-?\d{4})|(9[2-9]{1}\d{3}\-?\d{4}))$', 'pt-PT': r'^(\+?351)?9[1236]\d{7}$', 'pt-AO': r'^(\+244)\d{9}$', - 'ro-RO': r'^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$', + 'ro-RO': r'^(\+?4?0)\s?7\d{2}(/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$', 'ru-RU': r'^(\+?7|8)?9\d{9}$', 'si-LK': r'^(?:0|94|\+94)?(7(0|1|2|4|5|6|7|8)( |-)?)\d{7}$', 'sl-SI': r'^(\+386\s?|0)(\d{1}\s?\d{3}\s?\d{2}\s?\d{2}|\d{2}\s?\d{3}\s?\d{3})$', @@ -271,7 +267,7 @@ class IsMobileNumberOptions(TypedDict): mobile_number_patterns['fr-CH'] = mobile_number_patterns['de-CH'] mobile_number_patterns['it-CH'] = mobile_number_patterns['fr-CH'] -__default_options: IsMobileNumberOptions = { +__default_options = { 'strict_mode': False } @@ -279,29 +275,26 @@ class IsMobileNumberOptions(TypedDict): def is_mobile_number( input: str, locale: Tuple[List[Locals], Locals, 'any'] = 'any', - options: IsMobileNumberOptions = {} + options: dict = None ) -> bool: input = assert_string(input) - options = merge(options, __default_options) + options = merge(options or {}, __default_options) if options['strict_mode'] and not input.startswith('+'): return False if locale == 'any': - for item in mobile_number_patterns: - pattern = mobile_number_patterns[item] + for item, pattern in mobile_number_patterns.items(): if input.match(pattern): return True return False elif isinstance(locale, list): for item in locale: - if item in mobile_number_patterns: - pattern = mobile_number_patterns[item] + if pattern := mobile_number_patterns.get(item): if input.match(pattern): return True return False - elif locale in mobile_number_patterns: - pattern = mobile_number_patterns[locale] + elif pattern := mobile_number_patterns.get(locale): return input.match(pattern) - raise Exception('Invalid locale provided: {}'.format(locale)) + raise ValueError('Invalid locale provided: {}'.format(locale)) diff --git a/pyvalidator/is_odd.py b/pyvalidator/is_odd.py index 6bdc0e4..5be3604 100644 --- a/pyvalidator/is_odd.py +++ b/pyvalidator/is_odd.py @@ -6,7 +6,7 @@ def is_odd(input: Union[int, str]) -> bool: input = to_int(input) - if input == None: + if input is None: return False return bool(input % 2) diff --git a/pyvalidator/is_passport_number.py b/pyvalidator/is_passport_number.py index befb6b0..08f5947 100644 --- a/pyvalidator/is_passport_number.py +++ b/pyvalidator/is_passport_number.py @@ -2,63 +2,63 @@ from .utils.assert_string import assert_string passport_regex_by_country_code = { - "AM": "^[A-Z]{2}\d{7}$", # ARMENIA - "AR": "^[A-Z]{3}\d{6}$", # ARGENTINA - "AT": "^[A-Z]\d{7}$", # AUSTRIA - "AU": "^[A-Z]\d{7}$", # AUSTRALIA - "BA": "^[A-Z]\d{7}$", # BOSNIA AND HERZEGOVINA, - "BE": "^[A-Z]{2}\d{6}$", # BELGIUM - "BG": "^\d{9}$", # BULGARIA - "BR": "^[A-Z]{2}\d{6}$", # BRAZIL - "BY": "^[A-Z]{2}\d{7}$", # BELARUS - "CA": "^[A-Z]{2}\d{6}$", # CANADA - "CH": "^[A-Z]\d{7}$", # SWITZERLAND - "CN": "^G\d{8}$|^E(?![IO])[A-Z0-9]\d{7}$", # CHINA - "CY": "^[A-Z](\d{6}|\d{8})$", # CYPRUS - "CZ": "^\d{8}$", # CZECH REPUBLIC + "AM": r"^[A-Z]{2}\d{7}$", # ARMENIA + "AR": r"^[A-Z]{3}\d{6}$", # ARGENTINA + "AT": r"^[A-Z]\d{7}$", # AUSTRIA + "AU": r"^[A-Z]\d{7}$", # AUSTRALIA + "BA": r"^[A-Z]\d{7}$", # BOSNIA AND HERZEGOVINA, + "BE": r"^[A-Z]{2}\d{6}$", # BELGIUM + "BG": r"^\d{9}$", # BULGARIA + "BR": r"^[A-Z]{2}\d{6}$", # BRAZIL + "BY": r"^[A-Z]{2}\d{7}$", # BELARUS + "CA": r"^[A-Z]{2}\d{6}$", # CANADA + "CH": r"^[A-Z]\d{7}$", # SWITZERLAND + "CN": r"^G\d{8}$|^E(?![IO])[A-Z0-9]\d{7}$", # CHINA + "CY": r"^[A-Z](\d{6}|\d{8})$", # CYPRUS + "CZ": r"^\d{8}$", # CZECH REPUBLIC "DE": "^[CFGHJKLMNPRTVWXYZ0-9]{9}$", # GERMANY - "DK": "^\d{9}$", # DENMARK - "DZ": "^\d{9}$", # ALGERIA - "EE": "^([A-Z]\d{7}|[A-Z]{2}\d{7})$", # ESTONIA - "ES": "^[A-Z0-9]{2}([A-Z0-9]?)\d{6}$", # SPAIN - "FI": "^[A-Z]{2}\d{7}$", # FINLAND - "FR": "^\d{2}[A-Z]{2}\d{5}$", # FRANCE - "GB": "^\d{9}$", # UNITED KINGDOM - "GR": "^[A-Z]{2}\d{7}$", # GREECE - "HR": "^\d{9}$", # CROATIA - "HU": "^[A-Z]{2}(\d{6}|\d{7})$", # HUNGARY - "IE": "^[A-Z0-9]{2}\d{7}$", # IRELAND - "IN": "^[A-Z]{1}-?\d{7}$", # INDIA - "ID": "^[A-C]\d{7}$", # INDONESIA - "IR": "^[A-Z]\d{8}$", # IRAN - "IS": "^(A)\d{7}$", # ICELAND - "IT": "^[A-Z0-9]{2}\d{7}$", # ITALY - "JP": "^[A-Z]{2}\d{7}$", # JAPAN - "KR": "^[MS]\d{8}$", # SOUTH KOREA, REPUBLIC OF KOREA + "DK": r"^\d{9}$", # DENMARK + "DZ": r"^\d{9}$", # ALGERIA + "EE": r"^([A-Z]\d{7}|[A-Z]{2}\d{7})$", # ESTONIA + "ES": r"^[A-Z0-9]{2}([A-Z0-9]?)\d{6}$", # SPAIN + "FI": r"^[A-Z]{2}\d{7}$", # FINLAND + "FR": r"^\d{2}[A-Z]{2}\d{5}$", # FRANCE + "GB": r"^\d{9}$", # UNITED KINGDOM + "GR": r"^[A-Z]{2}\d{7}$", # GREECE + "HR": r"^\d{9}$", # CROATIA + "HU": r"^[A-Z]{2}(\d{6}|\d{7})$", # HUNGARY + "IE": r"^[A-Z0-9]{2}\d{7}$", # IRELAND + "IN": r"^[A-Z]{1}-?\d{7}$", # INDIA + "ID": r"^[A-C]\d{7}$", # INDONESIA + "IR": r"^[A-Z]\d{8}$", # IRAN + "IS": r"^(A)\d{7}$", # ICELAND + "IT": r"^[A-Z0-9]{2}\d{7}$", # ITALY + "JP": r"^[A-Z]{2}\d{7}$", # JAPAN + "KR": r"^[MS]\d{8}$", # SOUTH KOREA, REPUBLIC OF KOREA "LT": "^[A-Z0-9]{8}$", # LITHUANIA "LU": "^[A-Z0-9]{8}$", # LUXEMBURG - "LV": "^[A-Z0-9]{2}\d{7}$", # LATVIA + "LV": r"^[A-Z0-9]{2}\d{7}$", # LATVIA "LY": "^[A-Z0-9]{8}$", # LIBYA - "MT": "^\d{7}$", # MALTA - "MZ": "^([A-Z]{2}\d{7})|(\d{2}[A-Z]{2}\d{5})$", # MOZAMBIQUE - "MY": "^[AHK]\d{8}$", # MALAYSIA - "NL": "^[A-Z]{2}[A-Z0-9]{6}\d$", # NETHERLANDS - "PL": "^[A-Z]{2}\d{7}$", # POLAND - "PT": "^[A-Z]\d{6}$", # PORTUGAL - "RO": "^\d{8,9}$", # ROMANIA - "RS": "^\d{9}$", # SERBIA, - "RU": "^\d{9}$", # RUSSIAN FEDERATION - "SE": "^\d{8}$", # SWEDEN - "SL": "^(P)[A-Z]\d{7}$", # SLOVANIA - "SK": "^[0-9A-Z]\d{7}$", # SLOVAKIA - "TR": "^[A-Z]\d{8}$", # TURKEY - "UA": "^[A-Z]{2}\d{6}$", # UKRAINE - "US": "^\d{9}$", # UNITED STATES + "MT": r"^\d{7}$", # MALTA + "MZ": r"^([A-Z]{2}\d{7})|(\d{2}[A-Z]{2}\d{5})$", # MOZAMBIQUE + "MY": r"^[AHK]\d{8}$", # MALAYSIA + "NL": r"^[A-Z]{2}[A-Z0-9]{6}\d$", # NETHERLANDS + "PL": r"^[A-Z]{2}\d{7}$", # POLAND + "PT": r"^[A-Z]\d{6}$", # PORTUGAL + "RO": r"^\d{8,9}$", # ROMANIA + "RS": r"^\d{9}$", # SERBIA, + "RU": r"^\d{9}$", # RUSSIAN FEDERATION + "SE": r"^\d{8}$", # SWEDEN + "SL": r"^(P)[A-Z]\d{7}$", # SLOVENIA + "SK": r"^[0-9A-Z]\d{7}$", # SLOVAKIA + "TR": r"^[A-Z]\d{8}$", # TURKEY + "UA": r"^[A-Z]{2}\d{6}$", # UKRAINE + "US": r"^\d{9}$", # UNITED STATES } def is_passport_number(input: str, country_code: str) -> bool: - input = assert_string(input).sub(RegEx("\s", "g"), "").upper() + input = assert_string(input).sub(RegEx(r"\s", "g"), "").upper() is_valid_country = country_code in passport_regex_by_country_code diff --git a/pyvalidator/is_prime.py b/pyvalidator/is_prime.py index f2a8635..aff0301 100644 --- a/pyvalidator/is_prime.py +++ b/pyvalidator/is_prime.py @@ -6,7 +6,7 @@ def is_prime(input: Union[int, str]) -> bool: input = to_int(input) - if input == None: + if input is None: return False if input <= 1: diff --git a/pyvalidator/is_rgb_color.py b/pyvalidator/is_rgb_color.py index 0677386..a7760d9 100644 --- a/pyvalidator/is_rgb_color.py +++ b/pyvalidator/is_rgb_color.py @@ -1,9 +1,9 @@ from .utils.assert_string import assert_string -rgb_color = "^rgb\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\)$" -rgba_color = "^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$" -rgb_color_percent = "^rgb\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\)" -rgba_color_percent = "^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)" +rgb_color = r"^rgb\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\)$" +rgba_color = r"^rgba\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)$" +rgb_color_percent = r"^rgb\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\)" +rgba_color_percent = r"^rgba\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\.\d|1(\.0)?|0(\.0)?)\)" def is_rgb_color(input: str, include_percent_values: bool = True) -> bool: diff --git a/pyvalidator/is_semantic_version.py b/pyvalidator/is_semantic_version.py index c9a2fdf..2d28986 100644 --- a/pyvalidator/is_semantic_version.py +++ b/pyvalidator/is_semantic_version.py @@ -5,10 +5,10 @@ def is_semantic_version(input: str) -> bool: input = assert_string(input) - senabtic_version_pattern = RegEx( - "^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)" + - "(?:-((?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*))*))" + - "?(?:\+([0-9a-z-]+(?:\.[0-9a-z-]+)*))?$", "i" + semantic_version_pattern = RegEx( + r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)" + + r"(?:-((?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-z-][0-9a-z-]*))*))" + + r"?(?:\+([0-9a-z-]+(?:\.[0-9a-z-]+)*))?$", "i" ) - return senabtic_version_pattern.match(input) + return semantic_version_pattern.match(input) diff --git a/pyvalidator/is_strong_password.py b/pyvalidator/is_strong_password.py index 7d0e082..b4695e9 100644 --- a/pyvalidator/is_strong_password.py +++ b/pyvalidator/is_strong_password.py @@ -59,7 +59,7 @@ def analyze_password(pw: String) -> _Analysis: upper_case_regex = r"^[A-Z]$" lower_case_regex = r"^[a-z]$" number_regex = r"^[0-9]$" - symbol_regex = r"^[-#!$@%^&*()_+|~=`{}\[\]:\";'<>?,.\/ ]$" + symbol_regex = r"^[-#!$@%^&*()_+|~=`{}\[\]:\";'<>?,./ ]$" char_map = count_chars(pw) diff --git a/pyvalidator/is_url.py b/pyvalidator/is_url.py index 73af741..8fc722e 100644 --- a/pyvalidator/is_url.py +++ b/pyvalidator/is_url.py @@ -38,7 +38,7 @@ def is_url(input: str, options={}) -> bool: domains_pattern = domain.strip() else: domains_pattern = f"{domains_pattern}|{domain}" - domains_pattern = f"(?=.*({domains_pattern})\.)" + domains_pattern = rf"(?=.*({domains_pattern})\.)" top_level_domain_pattern = "" @@ -48,16 +48,16 @@ def is_url(input: str, options={}) -> bool: top_level_domain_pattern = domain.strip() else: top_level_domain_pattern = f"{top_level_domain_pattern}|{domain}" - top_level_domain_pattern = f"(\.({top_level_domain_pattern}))" + top_level_domain_pattern = rf"(\.({top_level_domain_pattern}))" else: top_level_domain_pattern = r"\.[a-z]{2,63}" - protocol_pattern = "" if options["no_scheme"] else r"((http(s)?):\/\/)?" + protocol_pattern = "" if options["no_scheme"] else r"((http(s)?)://)?" limit_domain_length = "{1,255}" base_url_pattern = fr"{protocol_pattern}(www\.)?(?!-)[(\-a-z0-9.]{limit_domain_length}[a-z0-9]{top_level_domain_pattern}" - path_pattern = r"\/?" if options["with_no_path"] else r"\b(\/[-a-zA-Z0-9()@:%_\+.~#?&//=]*)?" + path_pattern = r"/?" if options["with_no_path"] else r"\b(/[-a-zA-Z0-9()@:%_\+.~#?&//=]*)?" pattern = fr"^({domains_pattern}{base_url_pattern}{path_pattern})$" diff --git a/pyvalidator/utils/Classes/RegEx.py b/pyvalidator/utils/Classes/RegEx.py index 5ca4ee7..81fc1e2 100644 --- a/pyvalidator/utils/Classes/RegEx.py +++ b/pyvalidator/utils/Classes/RegEx.py @@ -11,7 +11,7 @@ class RegEx(object): def __init__(self, pattern: str, flag: FlagType = None) -> None: if not pattern: - raise Exception("Pattern not provided") + raise ValueError("Pattern not provided") if flag == 'i': self.pattern = re.compile(pattern, re.IGNORECASE) elif flag == 'g': @@ -45,6 +45,7 @@ def findall(self, target: str) -> Union[List, None]: return None return re.findall(self.pattern, target) + @staticmethod def compile(pattern) -> Pattern[AnyStr]: return re.compile(pattern) diff --git a/pyvalidator/utils/Classes/String.py b/pyvalidator/utils/Classes/String.py index a910881..646201c 100644 --- a/pyvalidator/utils/Classes/String.py +++ b/pyvalidator/utils/Classes/String.py @@ -12,7 +12,7 @@ def slice(self: T, start: int, end: Union[int, None] = None) -> T: sliced_string = slice(self, start, end) return String(sliced_string) - def split(self: T, separator=None) -> List: + def split(self: T, separator=None, *args, **kwargs) -> List: if bool(separator): string = self.__str__().split(separator) for index, item in enumerate(string): @@ -35,7 +35,7 @@ def sub(self: T, regex: Union[str, RegEx], replacement: str, flag: FlagType = No else: return String(RegEx.sub(regex.pattern, replacement, self.__str__())) - def rstrip(self: T) -> T: + def rstrip(self: T, *args, **kwargs) -> T: return String(self.__str__().rstrip()) def match(self: T, regex: Union[str, RegEx], flag: FlagType = None) -> bool: @@ -59,7 +59,7 @@ def starts_with(self: T, target: str, end: int = None) -> bool: else: return self.__str__().startswith(target, 0, end) - def findMatches(self: T, regex: Union[str, RegEx], flag: FlagType = None) -> Union[List, None]: + def find_matches(self: T, regex: Union[str, RegEx], flag: FlagType = None) -> Union[List, None]: if type(regex).__name__ == 'str' or type(regex).__name__ == 'String': pattern = RegEx(regex, flag) matches = pattern.findall(self.__str__()) @@ -75,9 +75,6 @@ def findMatches(self: T, regex: Union[str, RegEx], flag: FlagType = None) -> Uni def trim(self: T) -> T: return String(self.__str__().strip()) - def search(self: T, term: str) -> int: - return String(self.__str__().find(term)) - def substring(self: T, start: int, end: int = None) -> T: if not end: return String(self.__str__()[start:]) @@ -89,5 +86,5 @@ def search(self: T, pattern: str) -> Union[int, None]: def prefix(self: T, string: str) -> T: return String('' + string + self.__str__()) - def sufix(self: T, string: str) -> T: + def suffix(self: T, string: str) -> T: return String(self.__str__() + string) diff --git a/pyvalidator/utils/assert_string.py b/pyvalidator/utils/assert_string.py index 467e384..2feea9f 100644 --- a/pyvalidator/utils/assert_string.py +++ b/pyvalidator/utils/assert_string.py @@ -6,6 +6,6 @@ def assert_string(input: str) -> String: if not is_string: invalid_type = type(input).__name__ - raise Exception("Expected a string but received a {0}".format(invalid_type)) + raise ValueError(f"Expected a string but received a {invalid_type}") return String(input) diff --git a/pyvalidator/utils/math.py b/pyvalidator/utils/math.py index 30f2ee5..2c4a370 100644 --- a/pyvalidator/utils/math.py +++ b/pyvalidator/utils/math.py @@ -1,9 +1,9 @@ from typing import Union -def grather_then_check(input: str, min: Union[str, int, float, None]) -> bool: +def gather_then_check(input: str, min: Union[str, int, float, None]) -> bool: try: - if min == None: + if min is None: return True input_num = float(input) @@ -16,7 +16,7 @@ def grather_then_check(input: str, min: Union[str, int, float, None]) -> bool: def less_then_check(input: str, max: Union[str, int, float, None]) -> bool: try: - if max == None: + if max is None: return True input_num = float(input) diff --git a/pyvalidator/utils/merge.py b/pyvalidator/utils/merge.py index ebfc448..48f161e 100644 --- a/pyvalidator/utils/merge.py +++ b/pyvalidator/utils/merge.py @@ -1,7 +1,2 @@ -from typing import TypeVar - -T = TypeVar('T') - - -def merge(main_dict: T, default_dict: T) -> T: +def merge(main_dict: dict, default_dict: dict) -> dict: return {**default_dict, **main_dict} diff --git a/pyvalidator/utils/slice.py b/pyvalidator/utils/slice.py index 4ab45d8..f285394 100644 --- a/pyvalidator/utils/slice.py +++ b/pyvalidator/utils/slice.py @@ -2,7 +2,7 @@ def slice(val: str, start: int, end: Union[int, None]) -> str: - if end == None: + if end is None: return val[start:] return val[start:end] diff --git a/pyvalidator/utils/to_string.py b/pyvalidator/utils/to_string.py index cbb0cbc..4a28990 100644 --- a/pyvalidator/utils/to_string.py +++ b/pyvalidator/utils/to_string.py @@ -2,10 +2,11 @@ def to_string(input): - if type(input).__name__ == 'str': - return input - elif type(input).__name__ == 'int' or type(input).__name__ == 'float': + if isinstance(input, str): + # in case a custom string type is passed, return as an actual str return str(input) - elif type(input).__name__ == 'dict' or type(input).__name__ == 'list' or inspect(input): + elif isinstance(input, (int, float)): + return str(input) + elif isinstance(input, (dict, list)) or inspect.ismodule(input): return '[object Object]' return '' diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..21c1921 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,10 @@ +appdirs==1.4.4 +black==21.5b1 +click==7.1.2 +colorama==0.4.4 +docutils==0.18 +importlib-metadata==4.8.1 +isort==5.7.0 +readme-renderer==30.0 +typed-ast==1.4.3 +typing-extensions==3.7.4.3 diff --git a/requirements.txt b/requirements.txt index 81d00e3..fcb1540 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,13 +1,3 @@ -appdirs==1.4.4 -black==21.5b1 -click==7.1.2 -colorama==0.4.4 -docutils==0.18 -importlib-metadata==4.8.1 -isort==5.7.0 -readme-renderer==30.0 timestring==1.6.4 -typed-ast==1.4.3 typing==3.7.4.3 -typing-extensions==3.7.4.3 coverage==6.3.2 diff --git a/setup.py b/setup.py index dcc9c90..366e5e6 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ MAJOR = 0 MINOR = 14 -PATCH = 1 +PATCH = 2 VERSION = '{}.{}.{}'.format(MAJOR, MINOR, PATCH) DESCRIPTION = 'String validation and sanitization'