Skip to content

Commit

Permalink
Create validator_cidr.py
Browse files Browse the repository at this point in the history
  • Loading branch information
vanvianen committed Jul 7, 2024
1 parent 00ee87b commit bf20148
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions src/django-lan/utils/validators/validator_cidr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# -*- coding: utf-8 -*-


# =============================================================================
# Docstring
# =============================================================================

"""
Provides CIDR Validation Function
=================================
Validates CIDR (Classless Inter-Domain Routing) notations which are used to
describe the network portion and the host identifier portion of an IP address.
Links:
- https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
"""


# =============================================================================
# Import
# =============================================================================

# Import | Standard Library
from typing import Any
import ipaddress

# Import | Libraries
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

# Import | Local Modules


# =============================================================================
# Variables
# =============================================================================


# =============================================================================
# Functions
# =============================================================================

def validate_cidr(value: Any) -> None:
"""
CIDR Validation Function
========================
Validates that the provided value is a valid CIDR notation.
CIDR notation is a compact representation of an IP address and its
associated network mask. CIDR notation is a more flexible and universal
method to allocate IP addresses than the older system based on classes
(A, B, C).
Args:
value (Any): The CIDR notation to validate. It's expected to be a
string, but the function handles other types by attempting
conversion.
Raises:
ValidationError: If the provided value is not a valid CIDR notation.
Examples:
>>> validate_cidr("192.168.1.0/24")
None
>>> validate_cidr("192.168.1.0/35") # This example should raise a
ValidationError
ValidationError: Invalid CIDR notation
"""

try:
# Allows network address to be non-strict
ipaddress.ip_network(
value,
strict = False,
)
except ValueError:
raise ValidationError(
_("Invalid CIDR notation"),
code = "invalid_cidr",
)


# =============================================================================
# Public Interface
# =============================================================================

__all__ = [
"validate_cidr",
]

0 comments on commit bf20148

Please sign in to comment.