from datetime import date from typing import Union # 添加这行 # student/util/validator.py import re class Validator: @staticmethod def validate_id_card(id_card: str) -> bool: """验证身份证号码是否有效""" if not id_card or len(id_card) != 18: return False # 前17位必须是数字 if not id_card[:17].isdigit(): return False # 第18位可以是数字或X check_char = id_card[17].upper() if not (check_char.isdigit() or check_char == 'X'): return False # 校验码验证 factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] check_code_list = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'] sum_val = sum(int(id_card[i]) * factors[i] for i in range(17)) mod = sum_val % 11 check_code = check_code_list[mod] return check_char == check_code @staticmethod def validate_stu_id(stu_id: str) -> bool: """验证学号是否有效,格式示例:20230001""" pattern = r'^\d{8}$' # 假设学号为8位数字 return bool(re.match(pattern, stu_id)) @staticmethod def validate_name(name: str) -> bool: """验证姓名是否有效,2-20个字符,只能包含中文""" pattern = r'^[\u4e00-\u9fa5]{2,20}$' return bool(re.match(pattern, name)) @staticmethod def validate_height(height: int) -> bool: """验证身高是否在合理范围""" return 50 <= height <= 250 if height is not None else True @staticmethod def validate_weight(weight: float) -> bool: """验证体重是否在合理范围""" return 5 <= weight <= 300 if weight is not None else True @staticmethod def validate_enrollment_date(enrollment_date: Union[date, str], birthday: date) -> bool: """验证入学日期是否晚于出生日期""" if not enrollment_date: return True if isinstance(enrollment_date, str): try: enrollment_date = datetime.strptime(enrollment_date, '%Y-%m-%d').date() except ValueError: return False return enrollment_date >= birthday if birthday else True @staticmethod def validate_email(email: str) -> bool: """验证电子邮箱格式""" if not email: return True pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' return bool(re.match(pattern, email)) @staticmethod def validate_phone(phone: str) -> bool: """验证手机号码格式""" if not phone: return True pattern = r'^1[3-9]\d{9}$' return bool(re.match(pattern, phone))