validate with per-field error messages
Python
"""Validate payload fields and collect one clear message per bad field."""
import re
from typing import Any, Callable
Check = Callable[[Any], bool]
Rules = dict[str, tuple[Check, str]] # field -> (predicate, failure hint)
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$", re.IGNORECASE)
def validate(payload: dict[str, Any], rules: Rules, required: set[str]) -> dict[str, str]:
"""Return {field: message} for failing fields; empty dict means valid."""
errors: dict[str, str] = {}
for field, (check, hint) in rules.items():
value = payload.get(field)
if value is None or (isinstance(value, str) and not value.strip()):
if field in required:
errors[field] = f"{field} is required"
continue
if not check(value):
errors[field] = f"{field} must {hint}"
return errors
def is_email(value: Any) -> bool:
return isinstance(value, str) and EMAIL_RE.match(value) is not None
def between(low: float, high: float) -> Check:
"""Predicate factory for numeric ranges (bools are rejected)."""
def check(value: Any) -> bool:
if isinstance(value, bool) or not isinstance(value, (int, float)):
return False
return low <= value <= high
return check