diff --git a/src/validators/card.py b/src/validators/card.py index 484a9dc0..2538f5e2 100644 --- a/src/validators/card.py +++ b/src/validators/card.py @@ -11,7 +11,8 @@ def card_number(value: str, /): """Return whether or not given value is a valid generic card number. - This validator is based on [Luhn's algorithm][1]. + This validator is based on [Luhn's algorithm][1]. Numbers of fewer than 8 + or more than 19 digits are rejected, since no card number has such a length. [1]: https://github.com/mmcloughlin/luhn @@ -20,6 +21,8 @@ def card_number(value: str, /): True >>> card_number('4242424242424241') ValidationError(func=card_number, args={'value': '4242424242424241'}) + >>> card_number('18') + ValidationError(func=card_number, args={'value': '18'}) Args: value: @@ -31,6 +34,10 @@ def card_number(value: str, /): """ if not value: return False + if not 8 <= len(value) <= 19: + # an issuer identification number, an account number and a check digit + # take at least 8 digits; the longest card number has 19 + return False try: digits = list(map(int, value)) odd_sum = sum(digits[-1::-2]) diff --git a/tests/test_card.py b/tests/test_card.py index c17f5d95..e6b32400 100644 --- a/tests/test_card.py +++ b/tests/test_card.py @@ -43,6 +43,30 @@ def test_returns_true_on_valid_card_number(value: str): assert card_number(value) +# every value below passes the Luhn check, so only its length decides +@pytest.mark.parametrize("value", ["40128886", "6212345678901234569"]) +def test_returns_true_on_card_number_of_shortest_and_longest_length(value: str): + """Test returns true on card numbers of 8 and of 19 digits.""" + assert card_number(value) + + +@pytest.mark.parametrize( + "value", + [ + "0", + "00", + "18", + "0000000", + "4012886", + "62123456789012345676", + "00000000000000000000000000000000", + ], +) +def test_returns_failed_validation_on_card_number_of_impossible_length(value: str): + """Test returns failed validation on card numbers of fewer than 8 or more than 19 digits.""" + assert isinstance(card_number(value), ValidationError) + + @pytest.mark.parametrize( "value", [