Skip to content

Commit

Permalink
[#233] Improve Validator
Browse files Browse the repository at this point in the history
  • Loading branch information
danielmursa-dev committed Dec 23, 2024
1 parent e6ee4ab commit 7fe7f77
Showing 1 changed file with 75 additions and 40 deletions.
115 changes: 75 additions & 40 deletions src/openklant/components/klantinteracties/models/validators.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

from digid_eherkenning.validators import BSNValidator, Proef11ValidatorBase
from rest_framework import serializers
from digid_eherkenning.validators import BSNValidator

from .constants import (
PartijIdentificatorCodeObjectType,
Expand All @@ -10,20 +11,67 @@
)


def validate_digits(value: str) -> None:
if not value.isdigit():
raise serializers.ValidationError(
{
"partijIdentificator.objectId": _(
"ObjectId Verwacht een numerieke waarde."
)
}
)
from typing import List


class ObjectIdValidator:
"""
Validates an ObjectId based on digit check, length, and optional 11-proof check.
"""

list_size: List[int] = []
error_messages = {
"isdigit": "Expected a numerical value",
"length": "The length must be in: {list_size}",
"11proefnumber": "Invalid code",
}

def __init__(
self,
value: str,
list_size: List[int] = [],
check_11proefnumber: bool = False,
):
self.value = value
self.list_size = list_size
self.check_11proefnumber = check_11proefnumber

def validate_isdigit(self) -> None:
"""Validates that the value contains only digits."""
if not self.value.isdigit():
raise ValidationError(
self.error_messages["isdigit"],
code="invalid",
)

def validate_length(self) -> None:
"""Validates that the length of the value is within the allowed sizes."""
if len(self.value) not in self.list_size:
raise ValidationError(
self.error_messages["length"].format(list_size=self.list_size),
code="invalid",
)

def validate_11proefnumber(self) -> None:
"""Validates the value based on the 11-proof check."""
total = 0
for multiplier, char in enumerate(reversed(self.value), start=1):
if multiplier == 1:
total += -multiplier * int(char)
else:
total += multiplier * int(char)

if total % 11 != 0:
raise ValidationError(
self.error_messages["11proefnumber"],
code="invalid",
)

def validate_length(value: str, allowed_lengths: list) -> None:
if not len(value) in allowed_lengths:
raise serializers.ValidationError(_("Ongeldige veldlengte"))
def validate(self) -> None:
self.validate_isdigit()
self.validate_length()
if self.check_11proefnumber:
self.validate_11proefnumber()


class PartijIdentificatorValidator:
Expand Down Expand Up @@ -123,42 +171,29 @@ def validate_object_id(self) -> None:
):
return

if validate_object_type := getattr(
self, f"_validate_{self.code_soort_object_id}", None
):
validate_object_type()
else:
raise serializers.ValidationError(
{"partijIdentificator.objectId": _("Ongeldige codeSoortObjectId.")}
try:
getattr(self, f"_validate_{self.code_soort_object_id}")()
except ValidationError as error:
serializers.ValidationError(
{
"partijIdentificator.objectId": _(
"ObjectId ongeldig, reden: %s" % (error.message)
)
}
)

def _validate_bsn(self) -> None:
"""Validates the bsn object_id"""
try:
bsn = BSNValidator()
bsn(self.object_id)
except ValidationError:
raise serializers.ValidationError(
{"partijIdentificator.objectId": _("Ongeldig BSN.")}
)
ObjectIdValidator(self.object_id, [8, 9], True).validate()

def _validate_vestigingsnummer(self) -> None:
"""Validates the vestigingsNummer object_id"""
validate_digits(self.object_id)
validate_length(self.object_id, [12])
ObjectIdValidator(self.object_id, [12], False).validate()

def _validate_rsin(self) -> None:
"""Validates the rsin object_id"""
validate_digits(self.object_id)
try:
rsin = BSNValidator()
rsin(self.object_id)
except ValidationError:
raise serializers.ValidationError(
{"partijIdentificator.objectId": _("Ongeldig RSIN.")}
)
ObjectIdValidator(self.object_id, [8, 9], True).validate()

def _validate_kvknummer(self) -> None:
"""Validates the kvkNummer object_id"""
validate_digits(self.object_id)
validate_length(self.object_id, [8, 9])
ObjectIdValidator(self.object_id, [8], False).validate()

0 comments on commit 7fe7f77

Please sign in to comment.