|
| 1 | +def is_valid_cnh(cnh: str) -> bool: |
| 2 | + """ |
| 3 | + Validates the registration number for the Brazilian CNH (Carteira Nacional de Habilitação) that was created in 2022. |
| 4 | + Previous versions of the CNH are not supported in this version. |
| 5 | + This function checks if the given CNH is valid based on the format and allowed characters, |
| 6 | + verifying the verification digits. |
| 7 | +
|
| 8 | + Args: |
| 9 | + cnh (str): CNH string (symbols will be ignored). |
| 10 | +
|
| 11 | + Returns: |
| 12 | + bool: True if CNH has a valid format. |
| 13 | +
|
| 14 | + Examples: |
| 15 | + >>> is_valid_cnh("12345678901") |
| 16 | + False |
| 17 | + >>> is_valid_cnh("A2C45678901") |
| 18 | + False |
| 19 | + >>> is_valid_cnh("98765432100") |
| 20 | + True |
| 21 | + >>> is_valid_cnh("987654321-00") |
| 22 | + True |
| 23 | + """ |
| 24 | + cnh = "".join( |
| 25 | + filter(str.isdigit, cnh) |
| 26 | + ) # clean the input and check for numbers only |
| 27 | + |
| 28 | + if not cnh: |
| 29 | + return False |
| 30 | + |
| 31 | + if len(cnh) != 11: |
| 32 | + return False |
| 33 | + |
| 34 | + # Reject sequences as "00000000000", "11111111111", etc. |
| 35 | + if cnh == cnh[0] * 11: |
| 36 | + return False |
| 37 | + |
| 38 | + # cast digits to list of integers |
| 39 | + digits: list[int] = [int(ch) for ch in cnh] |
| 40 | + first_verificator = digits[9] |
| 41 | + second_verificator = digits[10] |
| 42 | + |
| 43 | + if not _check_first_verificator( |
| 44 | + digits, first_verificator |
| 45 | + ): # checking the 10th digit |
| 46 | + return False |
| 47 | + |
| 48 | + return _check_second_verificator( |
| 49 | + digits, second_verificator, first_verificator |
| 50 | + ) # checking the 11th digit |
| 51 | + |
| 52 | + |
| 53 | +def _check_first_verificator(digits: list[int], first_verificator: int) -> bool: |
| 54 | + """ |
| 55 | + Generates the first verification digit and uses it to verify the 10th digit of the CNH |
| 56 | + """ |
| 57 | + |
| 58 | + sum = 0 |
| 59 | + for i in range(9): |
| 60 | + sum += digits[i] * (9 - i) |
| 61 | + |
| 62 | + sum = sum % 11 |
| 63 | + result = 0 if sum > 9 else sum |
| 64 | + |
| 65 | + return result == first_verificator |
| 66 | + |
| 67 | + |
| 68 | +def _check_second_verificator( |
| 69 | + digits: list[int], second_verificator: int, first_verificator: int |
| 70 | +) -> bool: |
| 71 | + """ |
| 72 | + Generates the second verification and uses it to verify the 11th digit of the CNH |
| 73 | + """ |
| 74 | + sum = 0 |
| 75 | + for i in range(9): |
| 76 | + sum += digits[i] * (i + 1) |
| 77 | + |
| 78 | + result = sum % 11 |
| 79 | + |
| 80 | + if first_verificator > 9: |
| 81 | + result = result + 9 if (result - 2) < 0 else result - 2 |
| 82 | + |
| 83 | + if result > 9: |
| 84 | + result = 0 |
| 85 | + |
| 86 | + return result == second_verificator |
0 commit comments