File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/validators.tar
Back
iban.py 0000644 00000002067 15030212475 0006033 0 ustar 00 """IBAN.""" # standard import re # local from .utils import validator def _char_value(char: str): """A=10, B=11, ..., Z=35.""" return char if char.isdigit() else str(10 + ord(char) - ord("A")) def _mod_check(value: str): """Check if the value string passes the mod97-test.""" # move country code and check numbers to end rearranged = value[4:] + value[:4] return int("".join(_char_value(char) for char in rearranged)) % 97 == 1 @validator def iban(value: str, /): """Return whether or not given value is a valid IBAN code. Examples: >>> iban('DE29100500001061045672') # Output: True >>> iban('123456') # Output: ValidationError(func=iban, ...) Args: value: IBAN string to validate. Returns: (Literal[True]): If `value` is a valid IBAN code. (ValidationError): If `value` is an invalid IBAN code. """ return ( (re.match(r"^[a-z]{2}[0-9]{2}[a-z0-9]{11,30}$", value, re.IGNORECASE) and _mod_check(value)) if value else False ) ip_address.py 0000644 00000010536 15030212475 0007237 0 ustar 00 """IP Address.""" # standard from ipaddress import ( AddressValueError, IPv4Address, IPv4Network, IPv6Address, IPv6Network, NetmaskValueError, ) import re from typing import Optional # local from .utils import validator def _check_private_ip(value: str, is_private: Optional[bool]): if is_private is None: return True if ( any( value.startswith(l_bit) for l_bit in { "10.", # private "192.168.", # private "169.254.", # link-local "127.", # localhost "0.0.0.0", # loopback #nosec } ) or re.match(r"^172\.(?:1[6-9]|2\d|3[0-1])\.", value) # private or re.match(r"^(?:22[4-9]|23[0-9]|24[0-9]|25[0-5])\.", value) # broadcast ): return is_private return not is_private @validator def ipv4( value: str, /, *, cidr: bool = True, strict: bool = False, private: Optional[bool] = None, host_bit: bool = True, ): """Returns whether a given value is a valid IPv4 address. From Python version 3.9.5 leading zeros are no longer tolerated and are treated as an error. The initial version of ipv4 validator was inspired from [WTForms IPAddress validator][1]. [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py Examples: >>> ipv4('123.0.0.7') # Output: True >>> ipv4('1.1.1.1/8') # Output: True >>> ipv4('900.80.70.11') # Output: ValidationError(func=ipv4, args={'value': '900.80.70.11'}) Args: value: IP address string to validate. cidr: IP address string may contain CIDR notation. strict: IP address string is strictly in CIDR notation. private: IP address is public if `False`, private/local/loopback/broadcast if `True`. host_bit: If `False` and host bits (along with network bits) _are_ set in the supplied address, this function raises a validation error. ref [IPv4Network][2]. [2]: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network Returns: (Literal[True]): If `value` is a valid IPv4 address. (ValidationError): If `value` is an invalid IPv4 address. """ if not value: return False try: if cidr: if strict and value.count("/") != 1: raise ValueError("IPv4 address was expected in CIDR notation") return IPv4Network(value, strict=not host_bit) and _check_private_ip(value, private) return IPv4Address(value) and _check_private_ip(value, private) except (ValueError, AddressValueError, NetmaskValueError): return False @validator def ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True): """Returns if a given value is a valid IPv6 address. Including IPv4-mapped IPv6 addresses. The initial version of ipv6 validator was inspired from [WTForms IPAddress validator][1]. [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py Examples: >>> ipv6('::ffff:192.0.2.128') # Output: True >>> ipv6('::1/128') # Output: True >>> ipv6('abc.0.0.1') # Output: ValidationError(func=ipv6, args={'value': 'abc.0.0.1'}) Args: value: IP address string to validate. cidr: IP address string may contain CIDR annotation. strict: IP address string is strictly in CIDR notation. host_bit: If `False` and host bits (along with network bits) _are_ set in the supplied address, this function raises a validation error. ref [IPv6Network][2]. [2]: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Network Returns: (Literal[True]): If `value` is a valid IPv6 address. (ValidationError): If `value` is an invalid IPv6 address. """ if not value: return False try: if cidr: if strict and value.count("/") != 1: raise ValueError("IPv6 address was expected in CIDR notation") return IPv6Network(value, strict=not host_bit) return IPv6Address(value) except (ValueError, AddressValueError, NetmaskValueError): return False finance.py 0000644 00000006343 15030212475 0006526 0 ustar 00 """Finance.""" from .utils import validator def _cusip_checksum(cusip: str): check, val = 0, None for idx in range(9): c = cusip[idx] if c >= "0" and c <= "9": val = ord(c) - ord("0") elif c >= "A" and c <= "Z": val = 10 + ord(c) - ord("A") elif c >= "a" and c <= "z": val = 10 + ord(c) - ord("a") elif c == "*": val = 36 elif c == "@": val = 37 elif c == "#": val = 38 else: return False if idx & 1: val += val check = check + (val // 10) + (val % 10) return (check % 10) == 0 def _isin_checksum(value: str): check, val = 0, None for idx in range(12): c = value[idx] if c >= "0" and c <= "9" and idx > 1: val = ord(c) - ord("0") elif c >= "A" and c <= "Z": val = 10 + ord(c) - ord("A") elif c >= "a" and c <= "z": val = 10 + ord(c) - ord("a") else: return False if idx & 1: val += val return (check % 10) == 0 @validator def cusip(value: str): """Return whether or not given value is a valid CUSIP. Checks if the value is a valid [CUSIP][1]. [1]: https://en.wikipedia.org/wiki/CUSIP Examples: >>> cusip('037833DP2') True >>> cusip('037833DP3') ValidationFailure(func=cusip, ...) Args: value: CUSIP string to validate. Returns: (Literal[True]): If `value` is a valid CUSIP string. (ValidationError): If `value` is an invalid CUSIP string. """ return len(value) == 9 and _cusip_checksum(value) @validator def isin(value: str): """Return whether or not given value is a valid ISIN. Checks if the value is a valid [ISIN][1]. [1]: https://en.wikipedia.org/wiki/International_Securities_Identification_Number Examples: >>> isin('037833DP2') True >>> isin('037833DP3') ValidationFailure(func=isin, ...) Args: value: ISIN string to validate. Returns: (Literal[True]): If `value` is a valid ISIN string. (ValidationError): If `value` is an invalid ISIN string. """ return len(value) == 12 and _isin_checksum(value) @validator def sedol(value: str): """Return whether or not given value is a valid SEDOL. Checks if the value is a valid [SEDOL][1]. [1]: https://en.wikipedia.org/wiki/SEDOL Examples: >>> sedol('2936921') True >>> sedol('29A6922') ValidationFailure(func=sedol, ...) Args: value: SEDOL string to validate. Returns: (Literal[True]): If `value` is a valid SEDOL string. (ValidationError): If `value` is an invalid SEDOL string. """ if len(value) != 7: return False weights = [1, 3, 1, 7, 3, 9, 1] check = 0 for idx in range(7): c = value[idx] if c in "AEIOU": return False val = None if c >= "0" and c <= "9": val = ord(c) - ord("0") elif c >= "A" and c <= "Z": val = 10 + ord(c) - ord("A") else: return False check += val * weights[idx] return (check % 10) == 0 country.py 0000644 00000035107 15030212475 0006626 0 ustar 00 """Country.""" # local from validators.utils import validator # fmt: off _alpha3_to_alpha2 = { # A "ABW": "AW", "AFG": "AF", "AGO": "AO", "AIA": "AI", "ALB": "AL", "AND": "AD", "ANT": "AN", "ARE": "AE", "ARG": "AR", "ARM": "AM", "ASM": "AS", "ATA": "AQ", "ATF": "TF", "ATG": "AG", "AUS": "AU", "AUT": "AT", "AZE": "AZ", # B "BDI": "BI", "BEL": "BE", "BEN": "BJ", "BFA": "BF", "BGD": "BD", "BGR": "BG", "BHR": "BH", "BHS": "BS", "BIH": "BA", "BLR": "BY", "BLZ": "BZ", "BMU": "BM", "BOL": "BO", "BRA": "BR", "BRB": "BB", "BRN": "BN", "BTN": "BT", "BVT": "BV", "BWA": "BW", # C "CAF": "CF", "CAN": "CA", "CCK": "CC", "CHE": "CH", "CHL": "CL", "CHN": "CN", "CMR": "CM", "COD": "CD", "COG": "CG", "COK": "CK", "COL": "CO", "COM": "KM", "CPV": "CV", "CRI": "CR", "CUB": "CU", "CXR": "CX", "CYM": "KY", "CYP": "CY", "CZE": "CZ", # D "DEU": "DE", "DJI": "DJ", "DMA": "DM", "DNK": "DK", "DOM": "DO", "DZA": "DZ", # E "ECU": "EC", "EGY": "EG", "ERI": "ER", "ESH": "EH", "ESP": "ES", "EST": "EE", "ETH": "ET", # F "FIN": "FI", "FJI": "FJ", "FLK": "FK", "FRA": "FR", "FRO": "FO", "FSM": "FM", # G "GAB": "GA", "GBR": "GB", "GEO": "GE", "GGY": "GG", "GHA": "GH", "GIB": "GI", "GIN": "GN", "GLP": "GP", "GMB": "GM", "GNB": "GW", "GNQ": "GQ", "GRC": "GR", "GRD": "GD", "GRL": "GL", "GTM": "GT", "GUF": "GF", "GUM": "GU", "GUY": "GY", # H "HKG": "HK", "HMD": "HM", "HND": "HN", "HRV": "HR", "HTI": "HT", "HUN": "HU", # I "IDN": "ID", "IMN": "IM", "IND": "IN", "IOT": "IO", "IRL": "IE", "IRN": "IR", "IRQ": "IQ", "ISL": "IS", "ISR": "IL", "ITA": "IT", # J "JAM": "JM", "JEY": "JE", "JOR": "JO", "JPN": "JP", # K "KAZ": "KZ", "KEN": "KE", "KGZ": "KG", "KHM": "KH", "KIR": "KI", "KNA": "KN", "KOR": "KR", "KWT": "KW", # L "LAO": "LA", "LBN": "LB", "LBR": "LR", "LBY": "LY", "LCA": "LC", "LIE": "LI", "LKA": "LK", "LSO": "LS", "LTU": "LT", "LUX": "LU", "LVA": "LV", # M "MAC": "MO", "MAR": "MA", "MCO": "MC", "MDA": "MD", "MDG": "MG", "MDV": "MV", "MEX": "MX", "MHL": "MH", "MKD": "MK", "MLI": "ML", "MLT": "MT", "MMR": "MM", "MNE": "ME", "MNG": "MN", "MNP": "MP", "MOZ": "MZ", "MRT": "MR", "MSR": "MS", "MTQ": "MQ", "MUS": "MU", "MWI": "MW", "MYS": "MY", "MYT": "YT", # N "NAM": "NA", "NCL": "NC", "NER": "NE", "NFK": "NF", "NGA": "NG", "NIC": "NI", "NIU": "NU", "NLD": "NL", "NOR": "NO", "NPL": "NP", "NRU": "NR", "NZL": "NZ", # O "OMN": "OM", # P "PAK": "PK", "PAN": "PA", "PCN": "PN", "PER": "PE", "PHL": "PH", "PLW": "PW", "PNG": "PG", "POL": "PL", "PRI": "PR", "PRK": "KP", "PRT": "PT", "PRY": "PY", "PSE": "PS", "PYF": "PF", # Q "QAT": "QA", # R "REU": "RE", "ROU": "RO", "RUS": "RU", "RWA": "RW", # S "SAU": "SA", "SDN": "SD", "SEN": "SN", "SGP": "SG", "SGS": "GS", "SHN": "SH", "SJM": "SJ", "SLB": "SB", "SLE": "SL", "SLV": "SV", "SMR": "SM", "SOM": "SO", "SPM": "PM", "SRB": "RS", "STP": "ST", "SUR": "SR", "SVK": "SK", "SVN": "SI", "SWE": "SE", "SWZ": "SZ", "SYC": "SC", "SYR": "SY", # T "TCA": "TC", "TCD": "TD", "TGO": "TG", "THA": "TH", "TJK": "TJ", "TKL": "TK", "TKM": "TM", "TLS": "TL", "TON": "TO", "TTO": "TT", "TUN": "TN", "TUR": "TR", "TUV": "TV", "TWN": "TW", "TZA": "TZ", # U "UGA": "UG", "UKR": "UA", "UMI": "UM", "URY": "UY", "USA": "US", "UZB": "UZ", # V "VAT": "VA", "VCT": "VC", "VEN": "VE", "VGB": "VG", "VIR": "VI", "VNM": "VN", "VUT": "VU", # W "WLF": "WF", "WSM": "WS", # Y "YEM": "YE", # Z "ZAF": "ZA", "ZMB": "ZM", "ZWE": "ZW", } _calling_codes = { # A "ABW": "+297", "AFG": "+93", "AGO": "+244", "AIA": "+1-264", "ALB": "+355", "AND": "+376", "ANT": "+599", "ARE": "+971", "ARG": "+54", "ARM": "+374", "ASM": "+1-684", "ATA": "+672", "ATG": "+1-268", "AUS": "+61", "AUT": "+43", "AZE": "+994", # B "BDI": "+257", "BEL": "+32", "BEN": "+229", "BFA": "+226", "BGD": "+880", "BGR": "+359", "BHR": "+973", "BHS": "+1-242", "BIH": "+387", "BLR": "+375", "BLZ": "+501", "BMU": "+1-441", "BOL": "+591", "BRA": "+55", "BRB": "+1-246", "BRN": "+673", "BTN": "+975", "BWA": "+267", # C "CAF": "+236", "CAN": "+1", "CCK": "+61", "CHE": "+41", "CHL": "+56", "CHN": "+86", "CMR": "+237", "COD": "+243", "COG": "+242", "COK": "+682", "COL": "+57", "COM": "+269", "CPV": "+238", "CRI": "+506", "CUB": "+53", "CXR": "+61", "CYM": "+1-345", "CYP": "+357", "CZE": "+420", # D "DEU": "+49", "DJI": "+253", "DMA": "+1-767", "DNK": "+45", "DOM": "+1-809", "DZA": "+213", # E "ECU": "+593", "EGY": "+20", "ERI": "+291", "ESH": "+212", "ESP": "+34", "EST": "+372", "ETH": "+251", # F "FIN": "+358", "FJI": "+679", "FLK": "+500", "FRA": "+33", "FRO": "+298", "FSM": "+691", # G "GAB": "+241", "GBR": "+44", "GEO": "+995", "GGY": "+44-1481", "GHA": "+233", "GIB": "+350", "GIN": "+224", "GLP": "+590", "GMB": "+220", "GNB": "+245", "GNQ": "+240", "GRC": "+30", "GRD": "+1-473", "GRL": "+299", "GTM": "+502", "GUF": "+594", "GUM": "+1-671", "GUY": "+592", # H "HKG": "+852", "HMD": "+672", "HND": "+504", "HRV": "+385", "HTI": "+509", "HUN": "+36", # I "IDN": "+62", "IMN": "+44-1624", "IND": "+91", "IOT": "+246", "IRL": "+353", "IRN": "+98", "IRQ": "+964", "ISL": "+354", "ISR": "+972", "ITA": "+39", # J "JAM": "+1-876", "JEY": "+44-1534", "JOR": "+962", "JPN": "+81", # K "KAZ": "+7", "KEN": "+254", "KGZ": "+996", "KHM": "+855", "KIR": "+686", "KNA": "+1-869", "KOR": "+82", "KWT": "+965", # L "LAO": "+856", "LBN": "+961", "LBR": "+231", "LBY": "+218", "LCA": "+1-758", "LIE": "+423", "LKA": "+94", "LSO": "+266", "LTU": "+370", "LUX": "+352", "LVA": "+371", # M "MAC": "+853", "MAR": "+212", "MCO": "+377", "MDA": "+373", "MDG": "+261", "MDV": "+960", "MEX": "+52", "MHL": "+692", "MKD": "+389", "MLI": "+223", "MLT": "+356", "MMR": "+95", "MNE": "+382", "MNG": "+976", "MNP": "+1-670", "MOZ": "+258", "MRT": "+222", "MSR": "+1-664", "MTQ": "+596", "MUS": "+230", "MWI": "+265", "MYS": "+60", "MYT": "+262", # N "NAM": "+264", "NCL": "+687", "NER": "+227", "NFK": "+672", "NGA": "+234", "NIC": "+505", "NIU": "+683", "NLD": "+31", "NOR": "+47", "NPL": "+977", "NRU": "+674", "NZL": "+64", # O "OMN": "+968", # P "PAK": "+92", "PAN": "+507", "PCN": "+64", "PER": "+51", "PHL": "+63", "PLW": "+680", "PNG": "+675", "POL": "+48", "PRI": "+1-787", "PRK": "+850", "PRT": "+351", "PRY": "+595", "PSE": "+970", "PYF": "+689", # Q "QAT": "+974", # R "REU": "+262", "ROU": "+40", "RUS": "+7", "RWA": "+250", # S "SAU": "+966", "SDN": "+249", "SEN": "+221", "SGP": "+65", "SHN": "+290", "SJM": "+47", "SLB": "+677", "SLE": "+232", "SLV": "+503", "SMR": "+378", "SOM": "+252", "SPM": "+508", "SRB": "+381", "STP": "+239", "SUR": "+597", "SVK": "+421", "SVN": "+386", "SWE": "+46", "SWZ": "+268", "SYC": "+248", "SYR": "+963", # T "TCA": "+1-649", "TCD": "+235", "TGO": "+228", "THA": "+66", "TJK": "+992", "TKL": "+690", "TKM": "+993", "TLS": "+670", "TON": "+676", "TTO": "+1-868", "TUN": "+216", "TUR": "+90", "TUV": "+688", "TWN": "+886", "TZA": "+255", # U "UGA": "+256", "UKR": "+380", "UMI": "+1", "URY": "+598", "USA": "+1", "UZB": "+998", # V "VAT": "+379", "VCT": "+1-784", "VEN": "+58", "VGB": "+1-284", "VIR": "+1-340", "VNM": "+84", "VUT": "+678", # W "WLF": "+681", "WSM": "+685", # Y "YEM": "+967", # Z "ZAF": "+27", "ZMB": "+260", "ZWE": "+263" } _numeric = { "004", "008", "010", "012", "016", "020", "024", "028", "031", "032", "036", "040", "044", "048", "050", "051", "052", "056", "060", "064", "068", "070", "072", "074", "076", "084", "086", "090", "092", "096", "100", "104", "108", "112", "116", "120", "124", "132", "136", "140", "144", "148", "152", "156", "158", "162", "166", "170", "174", "175", "178", "180", "184", "188", "191", "192", "196", "203", "204", "208", "212", "214", "218", "222", "226", "231", "232", "233", "234", "238", "239", "242", "246", "248", "250", "254", "258", "260", "262", "266", "268", "270", "275", "276", "288", "292", "296", "300", "304", "308", "312", "316", "320", "324", "328", "332", "334", "340", "344", "348", "352", "356", "360", "364", "368", "372", "376", "380", "384", "388", "392", "398", "400", "404", "408", "410", "414", "417", "418", "422", "426", "428", "430", "434", "438", "440", "442", "446", "450", "454", "458", "462", "466", "470", "474", "478", "480", "484", "492", "496", "498", "499", "500", "504", "508", "512", "516", "520", "524", "528", "531", "533", "534", "535", "540", "548", "554", "558", "562", "566", "570", "574", "578", "580", "581", "583", "584", "585", "586", "591", "598", "600", "604", "608", "612", "616", "620", "624", "626", "630", "634", "638", "642", "643", "646", "652", "654", "659", "660", "662", "663", "666", "670", "674", "678", "682", "686", "688", "690", "694", "702", "703", "704", "705", "706", "710", "716", "724", "728", "729", "732", "740", "744", "748", "752", "756", "760", "762", "764", "768", "772", "776", "780", "784", "788", "792", "795", "796", "798", "800", "804", "807", "818", "826", "831", "832", "833", "834", "840", "850", "854", "858", "860", "862", "876", "882", "887", "894", } _currency_iso4217 = { # https://en.wikipedia.org/wiki/ISO_4217 "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CKD", "CLF", "CLP", "CNY", "COP", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "IEP", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KID", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VED", "VES", "VND", "VUV", "WST", "XAF", "XCD", "XDR", "XOF", "XPF", "YER", "ZAR", "ZMW", "ZWL" } _currency_symbols = { # https://en.wikipedia.org/wiki/Currency_sign_(generic) "؋", "฿", "₵", "₡", "¢", "$", "₫", "֏", "€", "ƒ", "₣", "₲", "₴", "₭", "₾", "£", "₺", "₼", "₦", "₱", "元", "圆", "圓", "﷼", "៛", "₽", "₹", "रू", "රු", "૱", "௹", "꠸", "Rs", "₪", "⃀" "৳", "₸", "₮", "₩", "¥", "円", "₿", "¤" } # fmt: on def _get_code_type(format_type: str): """Returns the type of country code.""" if format_type.isdecimal(): return "numeric" if format_type.isalpha(): if len(format_type) == 2: return "alpha2" if len(format_type) == 3: return "alpha3" return "invalid" @validator def calling_code(value: str, /): """Validates given calling code. This performs country's calling code validation. Examples: >>> calling_code('+91') # Output: True >>> calling_code('-31') # Output: ValidationError(func=calling_code, args={'value': '-31'}) Args: value: Country's calling code string to validate. Returns: (Literal[True]): If `value` is a valid calling code. (ValidationError): If `value` is an invalid calling code. """ if not value: return False return value in set(_calling_codes.values()) @validator def country_code(value: str, /, *, iso_format: str = "auto", ignore_case: bool = False): """Validates given country code. This performs a case-sensitive [ISO 3166][1] country code validation. [1]: https://www.iso.org/iso-3166-country-codes.html Examples: >>> country_code('GB', iso_format='alpha3') # Output: False >>> country_code('USA') # Output: True >>> country_code('840', iso_format='numeric') # Output: True >>> country_code('iN', iso_format='alpha2') # Output: False >>> country_code('ZWE', iso_format='alpha3') # Output: True Args: value: Country code string to validate. iso_format: ISO format to be used. Available options are: `auto`, `alpha2`, `alpha3` and `numeric`. ignore_case: Enable/Disable case-sensitive matching. Returns: (Literal[True]): If `value` is a valid country code. (ValidationError): If `value` is an invalid country code. """ if not value: return False if not (1 < len(value) < 4): return False if iso_format == "auto" and (iso_format := _get_code_type(value)) == "invalid": return False if iso_format == "alpha2": return ( value.upper() in set(_alpha3_to_alpha2.values()) if ignore_case else value in set(_alpha3_to_alpha2.values()) ) if iso_format == "alpha3": return value.upper() in _alpha3_to_alpha2 if ignore_case else value in _alpha3_to_alpha2 return value in _numeric if iso_format == "numeric" else False @validator def currency(value: str, /, *, skip_symbols: bool = True, ignore_case: bool = False): """Validates given currency code. This performs [ISO 4217][1] currency code/symbol validation. [1]: https://www.iso.org/iso-4217-currency-codes.html Examples: >>> currency('USD') # Output: True >>> currency('ZWX') # Output: ValidationError(func=currency, args={'value': 'ZWX'}) Args: value: Currency code/symbol string to validate. skip_symbols: Skip currency symbol validation. ignore_case: Enable/Disable case-sensitive matching. Returns: (Literal[True]): If `value` is a valid currency code. (ValidationError): If `value` is an invalid currency code. """ if not value: return False if not skip_symbols and value in _currency_symbols: return True if len(value) != 3: return False return value.upper() in _currency_iso4217 if ignore_case else value in _currency_iso4217 mac_address.py 0000644 00000001541 15030212475 0007363 0 ustar 00 """MAC Address.""" # standard import re # local from .utils import validator @validator def mac_address(value: str, /): """Return whether or not given value is a valid MAC address. This validator is based on [WTForms MacAddress validator][1]. [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L482 Examples: >>> mac_address('01:23:45:67:ab:CD') # Output: True >>> mac_address('00:00:00:00:00') # Output: ValidationError(func=mac_address, args={'value': '00:00:00:00:00'}) Args: value: MAC address string to validate. Returns: (Literal[True]): If `value` is a valid MAC address. (ValidationError): If `value` is an invalid MAC address. """ return re.match(r"^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$", value) if value else False hashes.py 0000644 00000007633 15030212475 0006401 0 ustar 00 """Hashes.""" # standard import re # local from .utils import validator @validator def md5(value: str, /): """Return whether or not given value is a valid MD5 hash. Examples: >>> md5('d41d8cd98f00b204e9800998ecf8427e') # Output: True >>> md5('900zz11') # Output: ValidationError(func=md5, args={'value': '900zz11'}) Args: value: MD5 string to validate. Returns: (Literal[True]): If `value` is a valid MD5 hash. (ValidationError): If `value` is an invalid MD5 hash. """ return re.match(r"^[0-9a-f]{32}$", value, re.IGNORECASE) if value else False @validator def sha1(value: str, /): """Return whether or not given value is a valid SHA1 hash. Examples: >>> sha1('da39a3ee5e6b4b0d3255bfef95601890afd80709') # Output: True >>> sha1('900zz11') # Output: ValidationError(func=sha1, args={'value': '900zz11'}) Args: value: SHA1 string to validate. Returns: (Literal[True]): If `value` is a valid SHA1 hash. (ValidationError): If `value` is an invalid SHA1 hash. """ return re.match(r"^[0-9a-f]{40}$", value, re.IGNORECASE) if value else False @validator def sha224(value: str, /): """Return whether or not given value is a valid SHA224 hash. Examples: >>> sha224('d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f') # Output: True >>> sha224('900zz11') # Output: ValidationError(func=sha224, args={'value': '900zz11'}) Args: value: SHA224 string to validate. Returns: (Literal[True]): If `value` is a valid SHA224 hash. (ValidationError): If `value` is an invalid SHA224 hash. """ return re.match(r"^[0-9a-f]{56}$", value, re.IGNORECASE) if value else False @validator def sha256(value: str, /): """Return whether or not given value is a valid SHA256 hash. Examples: >>> sha256( ... 'e3b0c44298fc1c149afbf4c8996fb924' ... '27ae41e4649b934ca495991b7852b855' ... ) # Output: True >>> sha256('900zz11') # Output: ValidationError(func=sha256, args={'value': '900zz11'}) Args: value: SHA256 string to validate. Returns: (Literal[True]): If `value` is a valid SHA256 hash. (ValidationError): If `value` is an invalid SHA256 hash. """ return re.match(r"^[0-9a-f]{64}$", value, re.IGNORECASE) if value else False @validator def sha384(value: str, /): """Return whether or not given value is a valid SHA384 hash. Examples: >>> sha384( ... 'cb00753f45a35e8bb5a03d699ac65007272c32ab0eded163' ... '1a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7' ... ) # Output: True >>> sha384('900zz11') # Output: ValidationError(func=sha384, args={'value': '900zz11'}) Args: value: SHA384 string to validate. Returns: (Literal[True]): If `value` is a valid SHA384 hash. (ValidationError): If `value` is an invalid SHA384 hash. """ return re.match(r"^[0-9a-f]{96}$", value, re.IGNORECASE) if value else False @validator def sha512(value: str, /): """Return whether or not given value is a valid SHA512 hash. Examples: >>> sha512( ... 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce' ... '9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af9' ... '27da3e' ... ) # Output: True >>> sha512('900zz11') # Output: ValidationError(func=sha512, args={'value': '900zz11'}) Args: value: SHA512 string to validate. Returns: (Literal[True]): If `value` is a valid SHA512 hash. (ValidationError): If `value` is an invalid SHA512 hash. """ return re.match(r"^[0-9a-f]{128}$", value, re.IGNORECASE) if value else False hostname.py 0000644 00000010057 15030212475 0006736 0 ustar 00 """Hostname.""" # standard from functools import lru_cache import re from typing import Optional from .domain import domain # local from .ip_address import ipv4, ipv6 from .utils import validator @lru_cache def _port_regex(): """Port validation regex.""" return re.compile( r"^\:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|" + r"6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3})$", ) @lru_cache def _simple_hostname_regex(): """Simple hostname validation regex.""" # {0,59} because two characters are already matched at # the beginning and at the end, making the range {1, 61} return re.compile(r"^(?!-)[a-z0-9](?:[a-z0-9-]{0,59}[a-z0-9])?(?<!-)$", re.IGNORECASE) def _port_validator(value: str): """Returns host segment if port is valid.""" if value.count("]:") == 1: # with ipv6 host_seg, port_seg = value.rsplit(":", 1) if _port_regex().match(f":{port_seg}"): return host_seg.lstrip("[").rstrip("]") if value.count(":") == 1: # with ipv4 or simple hostname host_seg, port_seg = value.rsplit(":", 1) if _port_regex().match(f":{port_seg}"): return host_seg return None @validator def hostname( value: str, /, *, skip_ipv6_addr: bool = False, skip_ipv4_addr: bool = False, may_have_port: bool = True, maybe_simple: bool = True, consider_tld: bool = False, private: Optional[bool] = None, # only for ip-addresses rfc_1034: bool = False, rfc_2782: bool = False, ): """Return whether or not given value is a valid hostname. Examples: >>> hostname("ubuntu-pc:443") # Output: True >>> hostname("this-pc") # Output: True >>> hostname("xn----gtbspbbmkef.xn--p1ai:65535") # Output: True >>> hostname("_example.com") # Output: True >>> hostname("123.5.77.88:31000") # Output: True >>> hostname("12.12.12.12") # Output: True >>> hostname("[::1]:22") # Output: True >>> hostname("dead:beef:0:0:0:0000:42:1") # Output: True >>> hostname("[0:0:0:0:0:ffff:1.2.3.4]:-65538") # Output: ValidationError(func=hostname, ...) >>> hostname("[0:&:b:c:@:e:f::]:9999") # Output: ValidationError(func=hostname, ...) Args: value: Hostname string to validate. skip_ipv6_addr: When hostname string cannot be an IPv6 address. skip_ipv4_addr: When hostname string cannot be an IPv4 address. may_have_port: Hostname string may contain port number. maybe_simple: Hostname string maybe only hyphens and alpha-numerals. consider_tld: Restrict domain to TLDs allowed by IANA. private: Embedded IP address is public if `False`, private/local if `True`. rfc_1034: Allow trailing dot in domain/host name. Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034). rfc_2782: Domain/Host name is of type service record. Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782). Returns: (Literal[True]): If `value` is a valid hostname. (ValidationError): If `value` is an invalid hostname. """ if not value: return False if may_have_port and (host_seg := _port_validator(value)): return ( (_simple_hostname_regex().match(host_seg) if maybe_simple else False) or domain(host_seg, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782) or (False if skip_ipv4_addr else ipv4(host_seg, cidr=False, private=private)) or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False)) ) return ( (_simple_hostname_regex().match(value) if maybe_simple else False) or domain(value, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782) or (False if skip_ipv4_addr else ipv4(value, cidr=False, private=private)) or (False if skip_ipv6_addr else ipv6(value, cidr=False)) ) __pycache__/ip_address.cpython-310.pyc 0000644 00000010330 15030212475 0013566 0 ustar 00 o �h^ � @ s� d Z ddlmZmZmZmZmZmZ ddlZddl m Z ddlmZ de de e fd d �Zeddddd �de dedede e def dd��Zedddd�de dededefdd��ZdS )zIP Address.� )�AddressValueError�IPv4Address�IPv4Network�IPv6Address�IPv6Network�NetmaskValueErrorN)�Optional� )� validator�value� is_privatec sD |d u rdS t � fdd�dD ��st�d� �st�d� �r|S | S )NTc 3 s � | ]}� � |�V qd S )N)� startswith)�.0�l_bit�r � �H/usr/local/CyberCP/lib/python3.10/site-packages/validators/ip_address.py� <genexpr> s � � �z$_check_private_ip.<locals>.<genexpr>> �10.�127.�0.0.0.0�169.254.�192.168.z^172\.(?:1[6-9]|2\d|3[0-1])\.z&^(?:22[4-9]|23[0-9]|24[0-9]|25[0-5])\.)�any�re�match)r r r r r �_check_private_ip s �� � �r TF)�cidr�strict�private�host_bitr r r r c C sp | sdS z&|r!|r| � d�dkrtd��t| | d�ot| |�W S t| �o)t| |�W S tttfy7 Y dS w )a Returns whether a given value is a valid IPv4 address. From Python version 3.9.5 leading zeros are no longer tolerated and are treated as an error. The initial version of ipv4 validator was inspired from [WTForms IPAddress validator][1]. [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py Examples: >>> ipv4('123.0.0.7') # Output: True >>> ipv4('1.1.1.1/8') # Output: True >>> ipv4('900.80.70.11') # Output: ValidationError(func=ipv4, args={'value': '900.80.70.11'}) Args: value: IP address string to validate. cidr: IP address string may contain CIDR notation. strict: IP address string is strictly in CIDR notation. private: IP address is public if `False`, private/local/loopback/broadcast if `True`. host_bit: If `False` and host bits (along with network bits) _are_ set in the supplied address, this function raises a validation error. ref [IPv4Network][2]. [2]: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network Returns: (Literal[True]): If `value` is a valid IPv4 address. (ValidationError): If `value` is an invalid IPv4 address. F�/r z*IPv4 address was expected in CIDR notation�r )�count� ValueErrorr r r r r )r r r r r r r r �ipv4) s ,�r% )r r r c C s\ | sdS z|r|r| � d�dkrtd��t| | d�W S t| �W S tttfy- Y dS w )ax Returns if a given value is a valid IPv6 address. Including IPv4-mapped IPv6 addresses. The initial version of ipv6 validator was inspired from [WTForms IPAddress validator][1]. [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py Examples: >>> ipv6('::ffff:192.0.2.128') # Output: True >>> ipv6('::1/128') # Output: True >>> ipv6('abc.0.0.1') # Output: ValidationError(func=ipv6, args={'value': 'abc.0.0.1'}) Args: value: IP address string to validate. cidr: IP address string may contain CIDR annotation. strict: IP address string is strictly in CIDR notation. host_bit: If `False` and host bits (along with network bits) _are_ set in the supplied address, this function raises a validation error. ref [IPv6Network][2]. [2]: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Network Returns: (Literal[True]): If `value` is a valid IPv6 address. (ValidationError): If `value` is an invalid IPv6 address. Fr! r z*IPv6 address was expected in CIDR notationr"