Files
knowai/utils/validation.ts
tobegold574 6a81b7bb13
Some checks reported errors
continuous-integration/drone/push Build was killed
feat(image): 新建 knowai-core:1.0.0 镜像并完成推送
- 搭建 api、auth、utils 等逻辑模块
- 通过 tsc、eslint、vitest 测试验证

BREAKING CHANGE: 新镜像分支
2025-11-10 20:20:25 +08:00

111 lines
2.7 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 验证工具
export const validationUtils = {
// 验证邮箱格式
isEmail: (email: string): boolean => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
},
// 验证手机号格式(中国大陆)
isPhoneNumber: (phone: string): boolean => {
const phoneRegex = /^1[3-9]\d{9}$/;
return phoneRegex.test(phone);
},
// 验证身份证号格式(中国大陆)
isIdCard: (idCard: string): boolean => {
const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
return idCardRegex.test(idCard);
},
// 验证密码强度
isStrongPassword: (password: string): boolean => {
// 至少8位包含大小写字母、数字和特殊字符
const strongPasswordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
return strongPasswordRegex.test(password);
},
// 验证是否为空
isEmpty: (value: unknown): boolean => {
if (value === null || value === undefined) {
return true;
}
if (typeof value === 'string') {
return value.trim() === '';
}
if (Array.isArray(value)) {
return value.length === 0;
}
if (typeof value === 'object') {
return Object.keys(value as Record<string, unknown>).length === 0;
}
return false;
},
// 验证数字范围
isInRange: (value: number, min: number, max: number): boolean => {
return value >= min && value <= max;
},
// 验证字符串长度
isLengthValid: (str: string, minLength: number, maxLength?: number): boolean => {
const length = str.length;
if (length < minLength) return false;
if (maxLength && length > maxLength) return false;
return true;
},
// 验证是否为数字
isNumber: (value: unknown): value is number => {
return typeof value === 'number' && !isNaN(value);
},
// 验证是否为整数
isInteger: (value: unknown): value is number => {
return validationUtils.isNumber(value) && Number.isInteger(value);
},
// 验证是否为正数
isPositive: (value: number): boolean => {
return value > 0;
},
// 验证是否为负数
isNegative: (value: number): boolean => {
return value < 0;
},
// 验证是否为偶数
isEven: (value: number): boolean => {
return value % 2 === 0;
},
// 验证是否为奇数
isOdd: (value: number): boolean => {
return value % 2 !== 0;
},
// 验证是否为闰年
isLeapYear: (year: number): boolean => {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
},
// 验证日期是否有效
isValidDate: (date: Date | string): boolean => {
const d = new Date(date);
// 检查日期是否有效
if (isNaN(d.getTime())) {
return false;
}
return true;
}
};