arbret/backend/utils/enum_validation.py
2025-12-25 18:27:59 +01:00

32 lines
867 B
Python

"""Utilities for validating enum values from strings."""
from enum import Enum
from typing import TypeVar
from exceptions import BadRequestError
T = TypeVar("T", bound=Enum)
def validate_enum(enum_class: type[T], value: str, field_name: str = "value") -> T:
"""
Validate and convert string to enum.
Args:
enum_class: The enum class to validate against
value: The string value to validate
field_name: Name of the field for error messages
Returns:
The validated enum value
Raises:
BadRequestError: If the value is not a valid enum member
"""
try:
return enum_class(value)
except ValueError:
valid_values = ", ".join(e.value for e in enum_class)
raise BadRequestError(
f"Invalid {field_name}: {value}. Must be one of: {valid_values}"
) from None