-
Notifications
You must be signed in to change notification settings - Fork 18
/
validators.py
47 lines (37 loc) · 1.66 KB
/
validators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class ValueCleaner(object):
def __call__(self, value):
"""Returns the value that is cleaned for database usage"""
return value
def display_value(self, value):
"""Returns the value that can be used for display"""
return self(value)
class UpperCaseValueCleaner(ValueCleaner):
def __call__(self, value):
"""Returns the value that is cleaned for database usage"""
if value is not None:
return value.upper().replace(' ', '').replace('-', '').replace('.', '')
return value
def _get_check_digit(to_check, factors, mod=11):
"""Method that calculates a check digit based on the following formula:
(10x_1+9x_2+8x_3+7x_4+6x_5+5x_6+4x_7+3x_8+2x_9+x_10) mod [mod]
where x_1 thru x_10 are values from to_check
and 10..1 are values from factors
Also known as the elfproef
"""
return sum(int(to_check[i]) * factors[i] for i in range(len(factors))) % mod
def _get_mod97_value(to_check, characters=None, mod=97):
"""Method that calculates a check digit based on the formula used for the mod97
check digit method. This method replaces all non-numeric values in the string with
two digits (i.e. A=10, B=11, etc) and then calculates a modulus of this value.
"""
digits = ""
for character in to_check:
if characters and character in characters:
digits += characters
elif character.isdigit():
digits += character
elif character.isalpha() and character.isupper():
digits += str(ord(character) - ord('A') + 10)
else:
raise ValueError("not a valid character: %s" % character)
return int(digits) % mod