forked from colinhacks/zod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
68 lines (63 loc) · 1.7 KB
/
index.ts
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
import * as z from "./src/index";
// try {
// const r = await z.object({
// val: z.string({ label: 'label val' }).nullable().superRefine(async (val, ctx) => {
// ctx.addIssue({
// code: 'invalid_type',
// received: 'undefined',
// expected: 'string',
// })
// return z.NEVER;
// })
// }).parseAsync({ val: '1' }, {
// fatalOnError: true
// })
// console.log(r)
// } catch (err) {
// console.log('err', err.formErrors.fieldErrors);
// }
// process.exit()
const schema = z.object({
name: z.string({
label: 'Name Label'
}).superRefine(async (val, ctx) => {
// await new Promise((resolve) => setTimeout(resolve, 2000));
// ctx.addIssue({
// code: z.ZodIssueCode.custom,
// message: `Custom message "${ctx.label}" issue`,
// fatal: true
// })
// return z.NEVER;
}),
lastName: z.string({
label: 'Last Name Label',
}),
email: z.string().email(),
age: z.number().min(18).max(19),
address: z.string(),
option: z.array(z.enum(['a'], { label: 'Option label' })),
optional: z.string({ label: 'optional label (inherit)' }).nullable().superRefine(async (val, ctx) => {
if(val){
ctx.addIssue({
code: 'invalid_type',
received: 'undefined',
expected: 'string',
})
return z.NEVER;
}
}),
}).important({
email: true
});
try {
const result = await schema.parseAsync(
{ name: "John", email: '[email protected]', age: 20, option: ['b'], optional: 'ha' }
// { name: "John", email: 'test', age: 20, option: ['a'] }
, {
fatalOnError: true,
});
console.log('res', result)
} catch (err) {
if(err instanceof z.ZodError)
console.log(err.formErrors.fieldErrors);
}