From 058fbac02a436b344ce448854c4b7cc6197972e4 Mon Sep 17 00:00:00 2001 From: JanakiRamChittineni <341781521+raams95@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:44:44 -0500 Subject: [PATCH] Check length and format of LEI numbers The validate() function only checked the ISO 7064 Mod 97, 10 checksum, so any string that passed the checksum was accepted, e.g. "1", an LEI with extra leading zeros or one with letters as check digits. This ensures that the number is 20 characters long, only contains letters and digits and ends with two numeric check digits. --- stdnum/lei.py | 8 +++++++- tests/test_lei.doctest | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/stdnum/lei.py b/stdnum/lei.py index 06b5c524..36dbd9b5 100644 --- a/stdnum/lei.py +++ b/stdnum/lei.py @@ -42,7 +42,7 @@ from stdnum.exceptions import * from stdnum.iso7064 import mod_97_10 -from stdnum.util import clean +from stdnum.util import clean, isdigits def compact(number: str) -> str: @@ -55,6 +55,12 @@ def validate(number: str) -> str: """Check if the number is valid. This checks the length, format and check digits.""" number = compact(number) + if not all(x in '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' for x in number): + raise InvalidFormat() + if len(number) != 20: + raise InvalidLength() + if not isdigits(number[-2:]): + raise InvalidFormat() mod_97_10.validate(number) return number diff --git a/tests/test_lei.doctest b/tests/test_lei.doctest index bc2d5a5b..4a055fe9 100644 --- a/tests/test_lei.doctest +++ b/tests/test_lei.doctest @@ -22,6 +22,29 @@ This file contains more detailed doctests for the stdnum.lei module. >>> from stdnum.exceptions import * +The number should be exactly 20 characters long. Leading zeros change the +length but not the checksum. + +>>> lei.validate('213800KUD8LAJWSQ9D15') +'213800KUD8LAJWSQ9D15' +>>> lei.validate('0213800KUD8LAJWSQ9D15') +Traceback (most recent call last): + ... +InvalidLength: ... +>>> lei.validate('1') +Traceback (most recent call last): + ... +InvalidLength: ... + + +The last two characters are the check digits and should be numeric. + +>>> lei.validate('213800KUD8LAJWSQ9DAD') +Traceback (most recent call last): + ... +InvalidFormat: ... + + These have been found online and should all be valid numbers. >>> numbers = '''