import re from typing import Optional, Union from datetime import datetime class ValidationUtil: """验证工具类""" @staticmethod def is_email(email: str) -> bool: """验证邮箱格式 Args: email: 邮箱地址 Returns: bool: 是否为有效邮箱 """ pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' return bool(re.match(pattern, email)) @staticmethod def is_phone(phone: str) -> bool: """验证手机号格式 Args: phone: 手机号码 Returns: bool: 是否为有效手机号 """ pattern = r'^1[3-9]\d{9}$' return bool(re.match(pattern, phone)) @staticmethod def is_id_card(id_card: str) -> bool: """验证身份证号格式 Args: id_card: 身份证号码 Returns: bool: 是否为有效身份证号 """ pattern = r'^\d{17}[\dXx]$' return bool(re.match(pattern, id_card)) @staticmethod def is_date(date_str: str, fmt: str = '%Y-%m-%d') -> bool: """验证日期格式 Args: date_str: 日期字符串 fmt: 日期格式 Returns: bool: 是否为有效日期 """ try: datetime.strptime(date_str, fmt) return True except ValueError: return False @staticmethod def is_number(value: Union[str, int, float]) -> bool: """验证是否为数字 Args: value: 输入值 Returns: bool: 是否为数字 """ if isinstance(value, (int, float)): return True try: float(value) return True except ValueError: return False @staticmethod def is_in_range(value: Union[int, float], min_val: Optional[Union[int, float]] = None, max_val: Optional[Union[int, float]] = None) -> bool: """验证数值是否在指定范围内 Args: value: 要验证的值 min_val: 最小值 max_val: 最大值 Returns: bool: 是否在范围内 """ if min_val is not None and value < min_val: return False if max_val is not None and value > max_val: return False return True @staticmethod def is_empty(value: Optional[Union[str, list, dict]]) -> bool: """验证值是否为空 Args: value: 输入值 Returns: bool: 是否为空 """ if value is None: return True if isinstance(value, str) and not value.strip(): return True if isinstance(value, (list, dict)) and not value: return True return False