71 lines
1.4 KiB
Python
71 lines
1.4 KiB
Python
"""Input validation utilities."""
|
|
|
|
import re
|
|
from datetime import time
|
|
from typing import Optional, Tuple
|
|
|
|
|
|
def validate_time_format(time_str: str) -> Optional[time]:
|
|
"""
|
|
Validate and parse time string in HH:MM format.
|
|
|
|
Args:
|
|
time_str: Time string to validate
|
|
|
|
Returns:
|
|
time object if valid, None otherwise
|
|
"""
|
|
# Remove extra whitespace
|
|
time_str = time_str.strip()
|
|
|
|
# Check format with regex
|
|
pattern = r'^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$'
|
|
match = re.match(pattern, time_str)
|
|
|
|
if not match:
|
|
return None
|
|
|
|
try:
|
|
hours = int(match.group(1))
|
|
minutes = int(match.group(2))
|
|
|
|
if 0 <= hours <= 23 and 0 <= minutes <= 59:
|
|
return time(hour=hours, minute=minutes)
|
|
except (ValueError, AttributeError):
|
|
pass
|
|
|
|
return None
|
|
|
|
|
|
def validate_days_interval(days_str: str) -> Optional[int]:
|
|
"""
|
|
Validate and parse days interval.
|
|
|
|
Args:
|
|
days_str: Days interval string to validate
|
|
|
|
Returns:
|
|
Integer days if valid (>0), None otherwise
|
|
"""
|
|
try:
|
|
days = int(days_str.strip())
|
|
if days > 0:
|
|
return days
|
|
except (ValueError, AttributeError):
|
|
pass
|
|
|
|
return None
|
|
|
|
|
|
def format_time_for_display(time_obj: time) -> str:
|
|
"""
|
|
Format time object for display.
|
|
|
|
Args:
|
|
time_obj: time object
|
|
|
|
Returns:
|
|
Formatted time string (HH:MM)
|
|
"""
|
|
return time_obj.strftime("%H:%M")
|