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
|
// 定义用户类型
interface User {
id: number;
name: string;
email: string;
age: number;
active: boolean;
roles: string[];
profile: {
bio: string;
avatar?: string;
};
}
// 创建用户验证器
const userValidator = createValidator.object<User>({
id: createValidator.number({ integerOnly: true, min: 1 }),
name: createValidator.string({ minLength: 2, maxLength: 50 }),
email: createValidator.string({
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Invalid email format'
}),
age: createValidator.number({ min: 18, max: 120, integerOnly: true }),
active: createValidator.boolean(),
roles: createValidator.array(createValidator.string()),
profile: createValidator.object({
bio: createValidator.string({ maxLength: 500 }),
avatar: createValidator.string({ required: false })
})
});
// 测试有效用户
const validUser: User = {
id: 1,
name: "John Doe",
email: "john@example.com",
age: 30,
active: true,
roles: ["user", "admin"],
profile: {
bio: "Software developer",
avatar: "https://example.com/avatar.jpg"
}
};
const validResult = userValidator.validate(validUser);
console.log("Valid user result:", validResult);
// 测试无效用户
const invalidUser = {
id: "not-a-number",
name: "J",
email: "invalid-email",
age: 15,
active: "yes",
roles: [1, "admin"],
profile: {
bio: "a".repeat(600)
}
};
const invalidResult = userValidator.validate(invalidUser);
console.log("Invalid user result:", invalidResult);
|