validation_util.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import re
  2. from typing import Optional, Union
  3. from datetime import datetime
  4. class ValidationUtil:
  5. """验证工具类"""
  6. @staticmethod
  7. def is_email(email: str) -> bool:
  8. """验证邮箱格式
  9. Args:
  10. email: 邮箱地址
  11. Returns:
  12. bool: 是否为有效邮箱
  13. """
  14. pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
  15. return bool(re.match(pattern, email))
  16. @staticmethod
  17. def is_phone(phone: str) -> bool:
  18. """验证手机号格式
  19. Args:
  20. phone: 手机号码
  21. Returns:
  22. bool: 是否为有效手机号
  23. """
  24. pattern = r'^1[3-9]\d{9}$'
  25. return bool(re.match(pattern, phone))
  26. @staticmethod
  27. def is_id_card(id_card: str) -> bool:
  28. """验证身份证号格式
  29. Args:
  30. id_card: 身份证号码
  31. Returns:
  32. bool: 是否为有效身份证号
  33. """
  34. pattern = r'^\d{17}[\dXx]$'
  35. return bool(re.match(pattern, id_card))
  36. @staticmethod
  37. def is_date(date_str: str, fmt: str = '%Y-%m-%d') -> bool:
  38. """验证日期格式
  39. Args:
  40. date_str: 日期字符串
  41. fmt: 日期格式
  42. Returns:
  43. bool: 是否为有效日期
  44. """
  45. try:
  46. datetime.strptime(date_str, fmt)
  47. return True
  48. except ValueError:
  49. return False
  50. @staticmethod
  51. def is_number(value: Union[str, int, float]) -> bool:
  52. """验证是否为数字
  53. Args:
  54. value: 输入值
  55. Returns:
  56. bool: 是否为数字
  57. """
  58. if isinstance(value, (int, float)):
  59. return True
  60. try:
  61. float(value)
  62. return True
  63. except ValueError:
  64. return False
  65. @staticmethod
  66. def is_in_range(value: Union[int, float],
  67. min_val: Optional[Union[int, float]] = None,
  68. max_val: Optional[Union[int, float]] = None) -> bool:
  69. """验证数值是否在指定范围内
  70. Args:
  71. value: 要验证的值
  72. min_val: 最小值
  73. max_val: 最大值
  74. Returns:
  75. bool: 是否在范围内
  76. """
  77. if min_val is not None and value < min_val:
  78. return False
  79. if max_val is not None and value > max_val:
  80. return False
  81. return True
  82. @staticmethod
  83. def is_empty(value: Optional[Union[str, list, dict]]) -> bool:
  84. """验证值是否为空
  85. Args:
  86. value: 输入值
  87. Returns:
  88. bool: 是否为空
  89. """
  90. if value is None:
  91. return True
  92. if isinstance(value, str) and not value.strip():
  93. return True
  94. if isinstance(value, (list, dict)) and not value:
  95. return True
  96. return False