|
| 1 | +import re |
| 2 | +from types import SimpleNamespace |
| 3 | +from .util import CHECK_DIGIT, validate_regexp, weighted_modulus_digit |
| 4 | + |
| 5 | + |
| 6 | +def normalize(id_number): |
| 7 | + """strip out useless characters/whitespaces""" |
| 8 | + return re.sub(r'[-. ]', '', id_number) |
| 9 | + |
| 10 | + |
| 11 | +def colombia_checksum(id_number: str) -> CHECK_DIGIT: |
| 12 | + """ |
| 13 | + Python version of |
| 14 | + https://github.com/anghelvalentin/CountryValidator/blob/master/CountryValidator/CountriesValidators/ColombiaValidator.cs |
| 15 | + """ |
| 16 | + numbers = [int(char) for char in list(normalize(id_number[:-1]))] |
| 17 | + numbers.reverse() |
| 18 | + modulus = weighted_modulus_digit(numbers, UniquePersonalID.WEIGHTS[0:len(numbers)], 11) |
| 19 | + if modulus == 11: |
| 20 | + return 0 |
| 21 | + elif modulus == 10: |
| 22 | + return 1 |
| 23 | + else: |
| 24 | + return modulus |
| 25 | + |
| 26 | + |
| 27 | +class UniquePersonalID: |
| 28 | + """ |
| 29 | + UniquePersonalID, NUIP, Número único de identidad personal |
| 30 | + https://en.wikipedia.org/wiki/Colombian_identity_card |
| 31 | + https://validatetin.com/colombia/# |
| 32 | + """ |
| 33 | + METADATA = SimpleNamespace(**{ |
| 34 | + 'iso3166_alpha2': 'CO', |
| 35 | + # length without insignificant chars |
| 36 | + 'min_length': 9, |
| 37 | + 'max_length': 10, |
| 38 | + # has parse function |
| 39 | + 'parsable': False, |
| 40 | + # has checksum function |
| 41 | + 'checksum': True, |
| 42 | + # regular expression to validate the id |
| 43 | + 'regexp': re.compile(r'^(\d{2,3}\.?\d{3}\.?\d{3}-?\d)$') |
| 44 | + }) |
| 45 | + |
| 46 | + WEIGHTS = [3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71] |
| 47 | + |
| 48 | + @staticmethod |
| 49 | + def validate(id_number: str) -> bool: |
| 50 | + """ |
| 51 | + Validate id number |
| 52 | + """ |
| 53 | + if not validate_regexp(id_number, UniquePersonalID.METADATA.regexp): |
| 54 | + return False |
| 55 | + return UniquePersonalID.checksum(id_number) == int(id_number[-1]) |
| 56 | + |
| 57 | + @staticmethod |
| 58 | + def checksum(id_number: str) -> CHECK_DIGIT: |
| 59 | + if not validate_regexp(id_number, UniquePersonalID.METADATA.regexp): |
| 60 | + return False |
| 61 | + return colombia_checksum(id_number) |
| 62 | + |
| 63 | + |
| 64 | +NUIP = UniquePersonalID |
| 65 | +"""alias of UniquePersonalID""" |
0 commit comments