|
| 1 | +"""Validation utilities for OpenProficiency library.""" |
| 2 | + |
| 3 | +import re |
| 4 | + |
| 5 | + |
| 6 | +def validate_kebab_case(value: str) -> None: |
| 7 | + """ |
| 8 | + Validate that a string follows kebab-case format. |
| 9 | +
|
| 10 | + Pattern: lowercase alphanumeric characters with hyphens as separators. |
| 11 | + Examples: "topic", "topic-id", "math-level-1" |
| 12 | +
|
| 13 | + Args: |
| 14 | + value: The string to validate |
| 15 | +
|
| 16 | + Raises: |
| 17 | + ValueError: If the value is not in valid kebab-case format |
| 18 | + """ |
| 19 | + if not value: |
| 20 | + raise ValueError("Value cannot be empty") |
| 21 | + |
| 22 | + # Pattern: starts and ends with alphanumeric, can have hyphens between |
| 23 | + pattern = r"^[a-z0-9]+(?:-[a-z0-9]+)*$" |
| 24 | + |
| 25 | + if not re.match(pattern, value): |
| 26 | + raise ValueError( |
| 27 | + f"Value must be in kebab-case format (lowercase alphanumeric with hyphens). " |
| 28 | + f"Got: '{value}'. Examples: 'topic', 'topic-id', 'math-level-1'" |
| 29 | + ) |
| 30 | + |
| 31 | + |
| 32 | +def validate_hostname(value: str) -> None: |
| 33 | + """ |
| 34 | + Validate that a string is a valid hostname or domain name. |
| 35 | +
|
| 36 | + Pattern: lowercase alphanumeric characters with hyphens and dots as separators. |
| 37 | + Examples: "example.com", "sub.example.com" |
| 38 | +
|
| 39 | + Args: |
| 40 | + value: The string to validate |
| 41 | +
|
| 42 | + Raises: |
| 43 | + ValueError: If the value is not in valid hostname format |
| 44 | + """ |
| 45 | + if not value: |
| 46 | + raise ValueError("Value cannot be empty") |
| 47 | + |
| 48 | + # Pattern: hostname components separated by dots (requires at least 2 components) |
| 49 | + # Each component: starts and ends with alphanumeric, can have hyphens between |
| 50 | + component_pattern = r"[a-z0-9]+(?:-[a-z0-9]+)*" |
| 51 | + pattern = f"^{component_pattern}(?:\\.{component_pattern})+$" |
| 52 | + |
| 53 | + if not re.match(pattern, value): |
| 54 | + raise ValueError( |
| 55 | + f"Value must be a valid hostname (lowercase alphanumeric with hyphens and dots). " |
| 56 | + f"Got: '{value}'. Examples: 'example.com','sub.example.com'" |
| 57 | + ) |
0 commit comments