med/media/validators.py

31 lines
947 B
Python
Raw Normal View History

2019-08-11 07:22:22 +00:00
# -*- mode: python; coding: utf-8 -*-
# Copyright (C) 2017-2019 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Based on https://github.com/secnot/django-isbn-field
"""
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from stdnum import isbn
def isbn_validator(raw_isbn):
"""Check string is a valid ISBN number"""
isbn_to_check = raw_isbn.replace('-', '').replace(' ', '')
2019-08-16 17:44:27 +00:00
if not isinstance(isbn_to_check, str):
raise ValidationError(_('Invalid ISBN: Not a string'))
2019-08-11 07:22:22 +00:00
if len(isbn_to_check) != 10 and len(isbn_to_check) != 13:
2019-08-16 17:44:27 +00:00
raise ValidationError(_('Invalid ISBN: Wrong length'))
2019-08-11 07:22:22 +00:00
if not isbn.is_valid(isbn_to_check):
2019-08-16 17:44:27 +00:00
raise ValidationError(_('Invalid ISBN: Failed checksum'))
2019-08-11 07:22:22 +00:00
if isbn_to_check != isbn_to_check.upper():
2019-08-16 17:44:27 +00:00
raise ValidationError(_('Invalid ISBN: Only upper case allowed'))
2019-08-11 07:22:22 +00:00
return True