1
1
# vat.py - functions for handling Irish VAT numbers
2
2
#
3
- # Copyright (C) 2012 Arthur de Jong
3
+ # Copyright (C) 2012, 2013 Arthur de Jong
4
4
#
5
5
# This library is free software; you can redistribute it and/or
6
6
# modify it under the terms of the GNU Lesser General Public
22
22
The Irish VAT number consists of 8 digits. The last digit is a check
23
23
letter, the second digit may be a number, a letter, "+" or "*".
24
24
25
- >>> compact ('IE 6433435F')
25
+ >>> validate ('IE 6433435F')
26
26
'6433435F'
27
- >>> is_valid('6433435F')
28
- True
29
- >>> is_valid('6433435E') # incorrect check digit
30
- False
31
- >>> is_valid('8D79739I') # old style number
32
- True
33
- >>> is_valid('8?79739J') # incorrect old style
34
- False
27
+ >>> validate('6433435E') # incorrect check digit
28
+ Traceback (most recent call last):
29
+ ...
30
+ InvalidChecksum: ...
31
+ >>> validate('8D79739I') # old style number
32
+ '8D79739I'
33
+ >>> validate('8?79739J') # incorrect old style
34
+ Traceback (most recent call last):
35
+ ...
36
+ InvalidFormat: ...
35
37
"""
36
38
39
+ from stdnum .exceptions import *
37
40
from stdnum .util import clean
38
41
39
42
@@ -54,20 +57,31 @@ def calc_check_digit(number):
54
57
return alphabet [sum ((8 - i ) * int (n ) for i , n in enumerate (number )) % 23 ]
55
58
56
59
57
- def is_valid (number ):
60
+ def validate (number ):
58
61
"""Checks to see if the number provided is a valid VAT number. This checks
59
62
the length, formatting and check digit."""
60
- try :
61
- number = compact (number )
62
- except :
63
- return False
64
- if len (number ) != 8 or not number [0 ].isdigit () or \
65
- not number [2 :7 ].isdigit ():
66
- return False
63
+ number = compact (number )
64
+ if not number [:1 ].isdigit () or not number [2 :7 ].isdigit ():
65
+ raise InvalidFormat ()
66
+ if len (number ) != 8 :
67
+ raise InvalidLength ()
67
68
if number [:7 ].isdigit ():
68
69
# new system
69
- return number [- 1 ] == calc_check_digit (number [:- 1 ])
70
- if number [1 ] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ+*' :
70
+ if number [- 1 ] != calc_check_digit (number [:- 1 ]):
71
+ raise InvalidChecksum ()
72
+ elif number [1 ] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ+*' :
71
73
# old system
72
- return number [- 1 ] == calc_check_digit (number [2 :- 1 ] + number [0 ])
73
- return False
74
+ if number [- 1 ] != calc_check_digit (number [2 :- 1 ] + number [0 ]):
75
+ raise InvalidChecksum ()
76
+ else :
77
+ raise InvalidFormat ()
78
+ return number
79
+
80
+
81
+ def is_valid (number ):
82
+ """Checks to see if the number provided is a valid VAT number. This checks
83
+ the length, formatting and check digit."""
84
+ try :
85
+ return bool (validate (number ))
86
+ except ValidationError :
87
+ return False
0 commit comments