You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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))