Skip to content

Commit

Permalink
Improve validation of CAS Registry Number
Browse files Browse the repository at this point in the history
This ensures that a leading 0 is treated as invalid.
  • Loading branch information
arthurdejong committed Oct 19, 2022
1 parent 7c2153e commit 09d595b
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions stdnum/casrn.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# casrn.py - functions for handling CAS Registry Numbers
#
# Copyright (C) 2017 Arthur de Jong
# Copyright (C) 2017-2022 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
Expand Down Expand Up @@ -32,12 +32,21 @@
Traceback (most recent call last):
...
InvalidChecksum: ...
>>> validate('012770-26-2')
Traceback (most recent call last):
...
InvalidFormat: ...
"""

import re

from stdnum.exceptions import *
from stdnum.util import clean, isdigits


_cas_re = re.compile(r'^[1-9][0-9]{1,6}-[0-9]{2}-[0-9]$')


def compact(number):
"""Convert the number to the minimal representation."""
number = clean(number, ' ').strip()
Expand All @@ -59,9 +68,7 @@ def validate(number):
number = compact(number)
if not 7 <= len(number) <= 12:
raise InvalidLength()
if not isdigits(number[:-5]) or not isdigits(number[-4:-2]):
raise InvalidFormat()
if number[-2] != '-' or number[-5] != '-':
if not _cas_re.match(number):
raise InvalidFormat()
if number[-1] != calc_check_digit(number[:-1]):
raise InvalidChecksum()
Expand Down

0 comments on commit 09d595b

Please sign in to comment.