Skip to content

Commit daf0b6f

Browse files
author
Kees Hink
committed
Added new validator: iban
1 parent fc21b65 commit daf0b6f

4 files changed

Lines changed: 76 additions & 0 deletions

File tree

‎CHANGES.rst‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
Changelog
22
---------
33

4+
0.8.0 (unreleased)
5+
^^^^^^^^^^^^^^^^^^
6+
7+
- Added new validator: ``iban``
8+
9+
410
0.7.0 (2014-09-07)
511
^^^^^^^^^^^^^^^^^^
612

‎tests/test_iban.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# -*- coding: utf-8 -*-
2+
import pytest
3+
import validators
4+
5+
6+
@pytest.mark.parametrize(('value',), [
7+
('GB82WEST12345698765432',),
8+
])
9+
def test_returns_true_on_valid_iban(value):
10+
assert validators.iban(value)
11+
12+
13+
@pytest.mark.parametrize(('value',), [
14+
('GB81WEST12345698765432',),
15+
])
16+
def test_returns_failed_validation_on_invalid_iban(value):
17+
result = validators.iban(value)
18+
assert isinstance(result, validators.ValidationFailure)

‎validators/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from .between import between
22
from .email import email
33
from .extremes import Min, Max
4+
from .iban import iban
45
from .ip_address import ipv4, ipv6
56
from .i18n import fi_business_id, fi_ssn
67
from .length import length

‎validators/iban.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import re
2+
from .utils import validator
3+
4+
regex = (
5+
r'^[A-Z]{2}[0-9]{2}[A-Z0-9]{13,30}$'
6+
)
7+
pattern = re.compile(regex)
8+
9+
10+
def char_value(char):
11+
"""A=10, B=11, ..., Z=35
12+
"""
13+
if char.isdigit():
14+
return int(char)
15+
else:
16+
return 10 + ord(char) - ord('A')
17+
18+
19+
def modcheck(value):
20+
"""Check if the value string passes the mod97-test.
21+
"""
22+
# move country code and check numbers to end
23+
rearranged = value[4:] + value[:4]
24+
# convert letters to numbers
25+
converted = [char_value(char) for char in rearranged]
26+
# interpret as integer
27+
integerized = int(''.join([str(i) for i in converted]))
28+
return (integerized % 97 == 1)
29+
30+
31+
@validator
32+
def iban(value):
33+
"""
34+
Return whether or not given value is a valid IBAN code.
35+
36+
If the value is a valid IBAN this function returns ``True``, otherwise
37+
:class:`~validators.utils.ValidationFailure`.
38+
39+
Examples::
40+
41+
>>> iban('DE29100500001061045672')
42+
True
43+
44+
>>> iban('123456')
45+
ValidationFailure(func=iban, ...)
46+
47+
.. versionadded:: 0.8
48+
49+
:param value: IBAN string to validate
50+
"""
51+
return pattern.match(value) and modcheck(value)

0 commit comments

Comments
 (0)