1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
|
// 验证规则类型
interface ValidationRule<T = any> {
message: string;
validate: (value: T) => boolean;
}
// 验证结果类型
interface ValidationResult {
isValid: boolean;
errors: Record<string, string[]>;
}
// 表单验证器类型
type Validator<T extends Record<string, any>> = {
[K in keyof T]: ValidationRule<T[K]>[];
};
// 创建表单验证函数
function createValidator<T extends Record<string, any>>(validator: Validator<T>) {
// 验证单个字段
function validateField<K extends keyof T>(fieldName: K, value: T[K]): string[] {
const rules = validator[fieldName] || [];
const errors: string[] = [];
for (const rule of rules) {
if (!rule.validate(value)) {
errors.push(rule.message);
}
}
return errors;
}
// 验证整个表单
function validateForm(formData: T): ValidationResult {
const errors: Record<string, string[]> = {};
let isValid = true;
Object.keys(validator).forEach((fieldName) => {
const fieldErrors = validateField(fieldName as keyof T, formData[fieldName as keyof T]);
if (fieldErrors.length > 0) {
errors[fieldName] = fieldErrors;
isValid = false;
}
});
return {
isValid,
errors,
};
}
// 获取单个规则函数
function getRule<K extends keyof T>(fieldName: K, index: number): ValidationRule<T[K]> | undefined {
return validator[fieldName]?.[index];
}
return {
validateField,
validateForm,
getRule,
};
}
// 常用验证规则
const required = <T>(message: string): ValidationRule<T> => ({
message,
validate: (value: T) => value !== undefined && value !== null && value !== '',
});
const minLength = (message: string, min: number): ValidationRule<string> => ({
message,
validate: (value: string) => typeof value === 'string' && value.length >= min,
});
const maxLength = (message: string, max: number): ValidationRule<string> => ({
message,
validate: (value: string) => typeof value === 'string' && value.length <= max,
});
const pattern = (message: string, regex: RegExp): ValidationRule<string> => ({
message,
validate: (value: string) => typeof value === 'string' && regex.test(value),
});
const min = (message: string, min: number): ValidationRule<number> => ({
message,
validate: (value: number) => typeof value === 'number' && value >= min,
});
const max = (message: string, max: number): ValidationRule<number> => ({
message,
validate: (value: number) => typeof value === 'number' && value <= max,
});
const email = (message: string = '请输入有效的邮箱地址'): ValidationRule<string> => ({
message,
validate: (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
});
// 表单数据类型
interface LoginForm {
username: string;
password: string;
rememberMe: boolean;
}
interface RegisterForm {
username: string;
email: string;
password: string;
confirmPassword: string;
agreeTerms: boolean;
}
// 登录表单验证器
const loginFormValidator = createValidator<LoginForm>({
username: [
required('用户名不能为空'),
minLength('用户名长度至少为3个字符', 3),
maxLength('用户名长度不能超过20个字符', 20),
],
password: [
required('密码不能为空'),
minLength('密码长度至少为6个字符', 6),
maxLength('密码长度不能超过50个字符', 50),
],
rememberMe: [],
});
// 注册表单验证器
const registerFormValidator = createValidator<RegisterForm>({
username: [
required('用户名不能为空'),
minLength('用户名长度至少为3个字符', 3),
maxLength('用户名长度不能超过20个字符', 20),
],
email: [
required('邮箱不能为空'),
email(),
],
password: [
required('密码不能为空'),
minLength('密码长度至少为6个字符', 6),
pattern('密码必须包含至少一个数字和一个字母', /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/),
],
confirmPassword: [], // 特殊规则,需要与密码比较
agreeTerms: [
{
message: '请同意服务条款',
validate: (value: boolean) => value === true,
},
],
});
// 使用示例 - 登录表单验证
function validateLoginForm(formData: LoginForm): ValidationResult {
return loginFormValidator.validateForm(formData);
}
// 使用示例 - 注册表单验证(包含跨字段验证)
function validateRegisterForm(formData: RegisterForm): ValidationResult {
// 先执行基本验证
const basicResult = registerFormValidator.validateForm(formData);
// 添加跨字段验证(确认密码)
if (formData.password !== formData.confirmPassword) {
basicResult.isValid = false;
basicResult.errors.confirmPassword = ['两次输入的密码不一致'];
}
return basicResult;
}
// 测试验证
const loginForm: LoginForm = {
username: 'john',
password: 'password123',
rememberMe: true,
};
const registerForm: RegisterForm = {
username: 'john_doe',
email: 'john@example.com',
password: 'Password123',
confirmPassword: 'Password123',
agreeTerms: true,
};
console.log('Login form validation:', validateLoginForm(loginForm));
console.log('Register form validation:', validateRegisterForm(registerForm));
|