Skip to content

Commit 6e635ba

Browse files
committed
Fix crash when validating credit card number
1 parent eab3dd8 commit 6e635ba

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

payments/fields.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from django.core import validators
99
from django.utils.translation import gettext_lazy as _
1010

11+
from .core import CARD_TYPES
1112
from .core import get_credit_card_issuer
1213
from .utils import get_month_choices
1314
from .utils import get_year_choices
@@ -34,16 +35,17 @@ def to_python(self, value):
3435
value = re.sub(r"[\s-]+", "", value)
3536
return super().to_python(value)
3637

37-
def validate(self, value):
38-
card_type, issuer_name = get_credit_card_issuer(value)
38+
def validate(self, value) -> None:
39+
card_type, _issuer_name = get_credit_card_issuer(value)
3940
if value in validators.EMPTY_VALUES and self.required:
4041
raise forms.ValidationError(self.error_messages["required"])
4142
if value and not self.cart_number_checksum_validation(self, value):
4243
raise forms.ValidationError(self.error_messages["invalid"])
4344
if value and self.valid_types is not None and card_type not in self.valid_types:
44-
valid_types = map(issuer_name, self.valid_types)
45+
card_type_names = {ct: name for _, ct, name in CARD_TYPES}
46+
valid_type_names = [card_type_names.get(t, t) for t in self.valid_types]
4547
error_message = self.error_messages["invalid_type"] % {
46-
"valid_types": ", ".join(valid_types)
48+
"valid_types": ", ".join(valid_type_names)
4749
}
4850
raise forms.ValidationError(error_message)
4951

payments/test_fields.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from __future__ import annotations
2+
3+
import pytest
4+
from django.core.exceptions import ValidationError
5+
6+
from payments.fields import CreditCardNumberField
7+
8+
9+
def test_validate_rejects_card_type_not_in_valid_types() -> None:
10+
# 4111111111111111 is a valid Visa test number (passes Luhn check)
11+
field = CreditCardNumberField(valid_types=["mastercard"])
12+
with pytest.raises(ValidationError, match="We accept only MasterCard"):
13+
field.validate("4111111111111111")

0 commit comments

Comments
 (0)