Skip to content

Commit 09d595b

Browse files
committed
Improve validation of CAS Registry Number
This ensures that a leading 0 is treated as invalid.
1 parent 7c2153e commit 09d595b

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

stdnum/casrn.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# casrn.py - functions for handling CAS Registry Numbers
22
#
3-
# Copyright (C) 2017 Arthur de Jong
3+
# Copyright (C) 2017-2022 Arthur de Jong
44
#
55
# This library is free software; you can redistribute it and/or
66
# modify it under the terms of the GNU Lesser General Public
@@ -32,12 +32,21 @@
3232
Traceback (most recent call last):
3333
...
3434
InvalidChecksum: ...
35+
>>> validate('012770-26-2')
36+
Traceback (most recent call last):
37+
...
38+
InvalidFormat: ...
3539
"""
3640

41+
import re
42+
3743
from stdnum.exceptions import *
3844
from stdnum.util import clean, isdigits
3945

4046

47+
_cas_re = re.compile(r'^[1-9][0-9]{1,6}-[0-9]{2}-[0-9]$')
48+
49+
4150
def compact(number):
4251
"""Convert the number to the minimal representation."""
4352
number = clean(number, ' ').strip()
@@ -59,9 +68,7 @@ def validate(number):
5968
number = compact(number)
6069
if not 7 <= len(number) <= 12:
6170
raise InvalidLength()
62-
if not isdigits(number[:-5]) or not isdigits(number[-4:-2]):
63-
raise InvalidFormat()
64-
if number[-2] != '-' or number[-5] != '-':
71+
if not _cas_re.match(number):
6572
raise InvalidFormat()
6673
if number[-1] != calc_check_digit(number[:-1]):
6774
raise InvalidChecksum()

0 commit comments

Comments
 (0)